- Home /
The question is answered, right answer was accepted
GetKeyUp not registering
I have a movement script and I want my character to turn around and move the other way rather than moonwalk backwards (forward animation playing but backward movement). This script works, but sometimes the GetKeyUp won't register and the character will be stuck facing the wrong way and you have to play with it to get them to face the right way again. Is there a simpler or better way to do this (maybe I should use an else instead of if)? Any input is welcome, and thanks in advance.
if (Input.GetKey (KeyCode.RightArrow)) {
animation.Play ("Allosaurus_Walk");
rigidbody.AddForce(Vector3.right *speedH);
}
if (Input.GetKeyUp (KeyCode.RightArrow))
{
animation.Stop ("Allosaurus_Walk");
animation.Play ("Allosaurus_Idle");
}
if (Input.GetKeyUp (KeyCode.LeftArrow))
{
animation.Stop ("Allosaurus_Walk");
animation.Play ("Allosaurus_Idle");
if (Input.GetKeyUp (KeyCode.LeftArrow))
{
transform.Rotate (0,180,0);
}
}
if (Input.GetKey (KeyCode.LeftArrow))
{
animation.Play ("Allosaurus_Walk");
rigidbody.AddForce(Vector3.left *speedH);
if (Input.GetKeyDown (KeyCode.LeftArrow))
{
transform.Rotate (0,180,0);
}
}
Answer by Eric5h5 · Feb 09, 2015 at 06:04 PM
If the code is in FixedUpdate, it must be moved to Update. KeyUp and Down events are only true for the one frame that they're activated, and FixedUpdate may well not run that frame.
Answer by hexagonius · Feb 09, 2015 at 05:18 PM
An easier approach could be:
create a vector3.zero
depending on left or right set x to 1 or -1
depending on x stop if 0 and start if not
set the rotation. Check out Quaternion.Euler. This way you dont turn around but face the correct direction
That sounds really simple, but it's new for me. What's Quaternion.Euler (I looked it up and it just says it rotates something around the z axis, so how is it different from transform.rotate)? Could you give me an example of this please? Thanks for your suggestion, it sounds promising and a lot more simple than what I had.
While Rotate is actually rotating your character every time it is called, Quaternion.Euler creates a look direction.
transform.rotation = Quaternion.Euler(0, -180, 0);
Will make your character look left, and it does not matter how often you call it. Provided that your Character's default orientation was looking right (its rotation values all 0)
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Flip over an object (smooth transition) 3 Answers
Objects not always Spawning At Correct Location 2 Answers
Problems after rotating character. 0 Answers
How would I go About making a flying player move forward, but also Around another object? 0 Answers