- Home /
Animation when you press key
Hello! Sorry for my english -) Help to write code.
Needed: We press the key - it will become animated, release the key - the animation stops.
I wrote the code, but it does not work as expected: When you press key the animation starts. When the key is released, it does not stop
if (Input.GetKey(KeyCode.RightArrow))// if pressed right
{
//Should play an animation running right
anim.SetFloat("Run", Mathf.Abs(runSpeed)); // Play the animation runs
transform.eulerAngles = new Vector3(0, 0f, 0); // For rotation in the opposite direction sprite
transform.Translate(runSpeed * Time.deltaTime, 0, 0); // run (runSpeed = 1f)
}
if (Input.GetKey(KeyCode.LeftArrow)) if pressed left
{
anim.SetFloat("Run", Mathf.Abs(runSpeed)); // Play the animation runs
transform.eulerAngles = new Vector3(0,180f,0); // For rotation in the opposite direction sprite
transform.Translate(runSpeed * Time.deltaTime, 0, 0); // run (runSpeed = 1f)
}
From Russia with love :-)
Thanks for the answer! This is not an option. I think when a key is pressed necessary stop the animation. How?
Answer by TheMidn1ght · Dec 03, 2013 at 12:12 AM
I think you are looking for GetKeyDown and GetKeyUp. This will check to see if the key has been pressed down/up and will only return true once per button press.
You also need a way to stop the player moving. Then you can do something like this.
if (Input.GetKeyUp(KeyCode.LeftArrow) || Input.GetKeyUp(KeyCode.RightArrow))
{
StopRunning();
}
Answer by Severok · Dec 03, 2013 at 09:24 PM
My working version
void Run()
{
if (Input.GetKey(KeyCode.RightArrow))
{
//Должна сыграть анимация бега вправо
anim.SetFloat("Run", Mathf.Abs(runSpeed));
transform.eulerAngles = new Vector3(0, 0f, 0);
transform.Translate(runSpeed * Time.deltaTime, 0, 0);
}
// Если кликаем на экран - игрок бежит влево
if (Input.GetKey(KeyCode.LeftArrow))
{
//Должна сыграть перевернутая анимация бега вправо
anim.SetFloat("Run", Mathf.Abs(runSpeed));
transform.eulerAngles = new Vector3(0, 180f, 0);
transform.Translate(runSpeed * Time.deltaTime, 0, 0);
}
if (Input.GetKeyUp(KeyCode.LeftArrow) || Input.GetKeyUp(KeyCode.RightArrow))
{
anim.SetFloat("Run", currentSpeed);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613123248im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Update iTween Path at Runtime 1 Answer
Play Specific Animations of an Object 1 Answer
Animation within Unity 1 Answer
Unassigned Reference Exception 4 Answers