- Home /
Question by
Omnipotential · May 22, 2021 at 09:11 PM ·
animationanimationevent
This code isn't allowing me to switch between idle and run animation
using UnityEngine;
public class bo : MonoBehaviour
{
public float MovementSpeed = 1;
public float JumpForce = 1;
public Animator anim;
private Rigidbody2D _rigidbody;
private void Start()
{
_rigidbody = GetComponent<Rigidbody2D>();
}
void Update()
{
var movement = Input.GetAxis("Horizontal");
transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * MovementSpeed;
if (Input.GetButtonDown("Jump") && Mathf.Abs(_rigidbody.velocity.y) < 0.001f)
{
_rigidbody.AddForce(new Vector2(0, JumpForce), ForceMode2D.Impulse);
if (Input.GetKeyDown(KeyCode.RightArrow)) anim.SetFloat("Speed", 10);
if (Input.GetKeyDown(KeyCode.LeftArrow)) anim.SetFloat("Speed", 10);
else anim.SetFloat("Speed", 0);
}
}
}
It isn't working even though I said if I clicked a key it should switch to run animation?
Comment
Answer by mohit19214 · May 24, 2021 at 06:51 AM
@Omnipotential in place of checking arrow keys just check movement value if it is zero use ideal animation and if it is not zero then use run animation. and as per your code these animations only play when jump button is pressed. I this does not work then let me know.
using UnityEngine;
public class bo : MonoBehaviour
{
public float MovementSpeed = 1;
public float JumpForce = 1;
public Animator anim;
private Rigidbody2D _rigidbody;
private void Start()
{
_rigidbody = GetComponent<Rigidbody2D>();
}
void Update()
{
var movement = Input.GetAxis("Horizontal");
transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * MovementSpeed;
if (Input.GetButtonDown("Jump") && Mathf.Abs(_rigidbody.velocity.y) < 0.001f)
{
_rigidbody.AddForce(new Vector2(0, JumpForce), ForceMode2D.Impulse);
}
if (movement != 0)
anim.SetFloat("Speed", 10);
else
anim.SetFloat("Speed", 0);
}
}
Don't envelop big code blocks in "`" characters as this is for in-line, very short snippets only.moderatory sidenote:
Your answer
Follow this Question
Related Questions
How to add new curves or animation events to an imported animation? 6 Answers
How to check if a animation is completed 1 Answer
Can the animation editor create local rotational data? 3 Answers
Keep boolean true whilst playing animation, then false 1 Answer
Adding animation clips via script 2 Answers