I have a space ship that will rotate clockwise or counter-clockwise depending on if the left or right button is pressed. I was using a virtual joystick and it was working fine but decided to change to left and right buttons. Now if click a button it will rotate to a fix position and stop each time i press the button, I'd like for it to move continuously in one direction while button held down and stop when released.
I'm using the unity standard assets with the cross platform input ButtonHadler script in conjunction with my "move" script.
void Update()
{
if (CrossPlatformInputManager.GetButtonDown("turn"))
{
TurnShip();
}
}
public void TurnShip()
{
transform.Rotate(Vector3.up * 50f * Time.deltaTime);
}
You're using GetButtonDown, which returns true only once when you press the button, and remains false until you release the button and press it again. Use GetButton instead.
Changing to GetButton was part of what I was missing but I had also set up my buttons up incorrectly I had accidentally added one event type with two function a pointer down and pointer up in the same event type instead of separating them.
Related
I wanna build a card game in Unity.
I want to player swipe cards left or right but I wanna show some tricks about what's gonna happen if they swipe left or right so if they grab the card (2D Image) and go a bit left or right a text will appear on image depends on side.
I tried to use swipe and use X axis change but It's not working properly.
Here is a basic pictured information about what i wanna build:
I would advise using the drag handlers system in unity to track where the card started, and trigger different effects at different distances / directions from its origin.
You can detect the drag of the card by implementing IBeginDragHandler, IDragHandler, IEndDragHandler on a script on your card object.
Begin is called when the object starts dragging, Drag is called during each frame its moving, and End is called when the object is dropped.
When a drag begins, you can cache the position where the card started. Then in Drag handler each frame you can check the distance of your card from where it started. Once it has moved more than a certain distance, you can trigger whatever tricks or effects you want to show.
Depending on how your coordinate space is set up, you could for example know left from right during drag updates such as:
// Inside of your on drag method, check each frame for where the card is
// If it has moved far enough, trigger an effect
if (Vector3.Distance(dragStartPosition, transfom.position) > yourTriggerDistance) {
// if X is greater, the card moved right
if (transform.position.x > dragStartPosition.x) {
// Trigger Right swipe text
ShowSomeRightSwipeText();
}
// otherwise, X is smaller, so the card has moved left by the required distance
else {
// Trigger left swipe text
ShowSomeLeftSwipeText();
}
}
Also please remember that:
In order for these interfaces to work, you need to have a Physics 2D Raycaster attached to your camera in the scene.
You need to make sure you have an Event System in the scene as well.
The above two things are often asked issues here regarding detecting object dragging.
The following code locks the cursor only when I left click my mouse after pressing Escape Key. Can anyone suggest me a way to overcome this problem?
public class lockCursor : MonoBehaviour
{
public bool locked = true;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
if (locked == false)
{
Debug.Log("locked");
Cursor.lockState = CursorLockMode.Locked;
locked = true;
}
else
{
Debug.Log("Unlocked");
Cursor.lockState = CursorLockMode.None;
locked = false;
}
}
}
}
As said in the API for Cursor.lockState
In the Editor the cursor is automatically reset when escape is pressed, or on switching applications.
Due to escape having a special role itself within the Unity Editor the GameView loses focus when pressing it.
There is not really a (trivial) way around this since it would require to intercept they keypress before the Unity Editor itself gets the chance to handle that escape press. (Which would always happen before it is passed on to the player -> your code.)
What you can do however would be simply use a different KeyCode only for the editor and escape only in a build like e.g.
#if UNITY_EDITOR
if(Input.GetKeyDown(KeyCode.E))
#else
if(Input.GetKeyDown(KeyCode.Escape))
#endif
{
...
You can replace the E with any other KeyCode you wish to use to "simulate the escape key" only within the Unity Editor itself. (Also see Platform dependent compilation)
As derHugo mentioned in his comment, your issue lies in the API for Cursor.lockState where it says:
"In the Editor the cursor is automatically reset when escape is
pressed, or on switching applications. In the Standalone Player you
have full control over the mouse cursor, but switching applications
still resets the cursor."
When you go to press Escape, it removes you from the application/Game Window. This is why it'll appear like your cursor is no longer locked. This is also why it goes into it's locked state as soon as you click back into the game. The same thing can be demonstrated by using your code, starting the game and then switching into another window on another monitor. Then move your mouse back over to the screen where the Game Window is. It'll appear as though it is no longer in a locked state... that is until you click in the game and it recognizes the cursor again.
To solve your problem, I would recommend using any key other than KeyCode.Escape. Maybe KeyCode.Space like the API shows.
Also, to further demonstrate the issue here, once you switch the code to use KeyCode.Space, press Space to lock the cursor and then try pressing Escape. Again you'll see that it appears to be unlocked until you press the Left Mouse Button in the Game Window again. This is because the Game thinks that you are no longer in the Game Window once you press Escape.
Hope this helps!
I recently thought about adding a InGame Button to my Game. It's not a GUI or UI Button, it's a Block, added to a Wall for example.
Dummy Code:
OnTriggerEnter(c:Collider) {
if(c.gameObject.tag =="Player")
{
//Text = "E to interact!"
if(key.pressed("e")
{
//Connect the Button to a specific Block, play a Animation
}
}
}
So how do I connect a specific Block to the Button, and if I press e, Play the Animation just on the specific block? Please keep in mind that I'm new in Unity.
Thanks for helping out!
I don't know if you already managed to create your animation, so I-ll explain from scratch. When in the editor, select your Door and press ctrl+6 to open the animation window. From here you can animate your block. When you will be done creating the animation, your block object will have a new script attached to it: an animator. You can see the animator state machine in the animator window
These are two different things:
Animation: Defines a single animation (translation, rotation, change of color, ...)
Animator: defines when an animation occurs for the corresponding gameobject. An animator can have variables (for example, a bool) that define which is the next animation to be played
Any object can have an animator (your button can have one to move when it is pressed. You door can have another one to open / close)
For instance, in your button animator, you should have three states: Idle, Press, UnPress.
The state Press will contain the animation "press" with speed 1. The state UnPress will contain the animation "press with speed -1
Then, still in the animator window, You will create links between Idle and the two other states and add a trigger condition called "OnPress" (for example)
You can do the same to animate your door
In your Button code, you will then write
public Animator Door; // In the editor, give a reference to your door. It must have an Animator script for this to work
OnTriggerEnter(c:Collider) {
if(c.gameObject.tag =="Player")
{
//Text = "E to interact!"
if(key.pressed("e")
{
GetComponent<Animator>().SetTrigger("OnPress"); // The button's animator goes to "pressed" state
Door.SetTrigger("Open"); // The door's animator goes to "open" state
}
}
}
Then you could add another trigger to unpress the button
One more thing: When you say "Connect the button to the block", I feel like you misunderstood something: Your button script should be already added to the block in the editor
Look at these two links for more information on animations:
http://docs.unity3d.com/Manual/animeditor-UsingAnimationEditor.html
http://docs.unity3d.com/Manual/AnimatorWindow.html
I'm makimg a game in Unity using C# developed for Android. I'm testing using Unity Remote 4. I was just wondering if a sprite can be used as a button in Unity rather than the button made in Component -> UI -> Button.
I've tried this:
private void Update()
{
if (Input.touchCount > 0)
Application.LoadLevel("startScene");
}
Which does work. The button is being used to switch from the main menu to an options menu.
Ideally, I want the button to be in the same place in the options menu to be used to go back to the main menu. The problem then is that because the scenes switch instantly, the scenes switch between each other over and over I guess because the next scene gets the touch input as well.
How can I delay the time between the scenes switching, or is there a better way to use sprites as a button??
You can create a menu system which is persistent in scenes. Have a look at This Tutorial Video for guide
Usually buttons perform their function once a tap has been performed. A tap is a press and release on the button. What you are doing is performing your function on a press which is causing your buttons to be triggered continuously while you hold your finger.
Pseudo code:
If a finger presses on the sprite
If the same finger is release on the sprite
The button has been pressed.
You can use ray casting to detect touch on the sprite
private void Update()
{
if (Input.touchCount != 1) return;
var wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
var touchPos = new Vector2(wp.x, wp.y);
if (collider2D == Physics2D.OverlapPoint(touchPos))
{
// Your code
}
}
This is one way that has worked for me:
Add the sprite that you will use as the background of the button to the stage.
Add a Collider and mark it as a trigger.
Assign a script where you add any of the following functions depending on your case.
private void OnMouseDown () {
// Runs by pressing the button
}
private void OnMouseUp () {
// Runs when button is released
}
I just bought NGUI and need some help...
Right now my 2D character is moving left and right with the left and right arrows.
I have the left and right arrows setup to do this in the input manager.
I made left and right arrow buttons with NGUI added them to my UI Root.
How do I get it to mimic the left arrow being pressed when I press the left arrow button?
Or is there a way to add the left arrow button being pressed to the input manager?
All I want to do is make the left arrow button act like when I press the left arrow key and the same for the right.
If there is another way to do it without NGUI thats fine too.
I just want to be able to move left and right when I press the left and right buttons on a mobile device.
I have been stuck on this for like 6 hours now, and can't figure it out.
Any help would be greatly appreciated!
Thanks!
Heres an example of how I'm moving the character
float h = Input.GetAxis("Horizontal");
// The Speed animator parameter is set to the absolute value of the horizontal input.
anim.SetFloat("Speed", Mathf.Abs(h));
// If the player is changing direction (h has a different sign to velocity.x) or hasn't reached maxSpeed yet...
if(h * rigidbody2D.velocity.x < maxSpeed)
// ... add a force to the player.
rigidbody2D.AddForce(Vector2.right * h * moveForce);
if (Mathf.Abs(rigidbody2D.velocity.x) > maxSpeed)
rigidbody2D.velocity = new Vector2(Mathf.Sign(rigidbody2D.velocity.x) * maxSpeed, rigidbody2D.velocity.y);
The effect of the button is processed in the OnPress (bool isDown) function. By default, it is called everytime you hover over the button.
If I understood you correctly, you want to simulate this hovering while pressing the related arrow key on the keyboard.
In order to do this, you would have to call the OnPress (bool isDown) function yourself. Try to add this line to your code:
SendMessage("OnPress", true);
This will call the OnPress function on all scripts added to the gameobject.
To call the function on a special gameObject just add a public variable go and then go with go.SendMessage("OnPress", true);
Hope, this will help. :)