- Home /
Question by
RedRightHand- · Oct 10, 2021 at 05:00 PM ·
2d2d animationattack
How to stop movement for a character while attack animation using while function?
Hello!
I'm a Unity noob. I have successfully implemented animations for jumping, running and attacking to a character, but I want to disable movement while the attack animation is playing. This is the relevant code I used for the horizontal movement and attack. The solutions I've read haven't really helped me, but I have an idea to accomplish what I want.
I had hoped that a "while" would work, but it doesn't. There's no error, but I would like to know how to implement this idea correctly.
public float Speed;
private Rigidbody2D Rigidbody2D;
private Animator Animator;
private float Horizontal;
private void Start()
{
Rigidbody2D = GetComponent<Rigidbody2D>();
Animator = GetComponent<Animator>();
}
private void Update()
{
Horizontal = Input.GetAxisRaw("Horizontal");
if (Horizontal < 0.0f) transform.localScale = new Vector3(-1.0f, 1.0f, 1.0f);
else if (Horizontal > 0.0f) transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
Animator.SetBool("Run", Horizontal != 0.0f);
if (Input.GetKeyDown(KeyCode.F))
{
Attack();
}
//This is the "solution" I tried, but didn't work. It's an analog for .IsPlaying() from the animation component.
while (Animator.GetCurrentAnimatorStateInfo(0).IsName("CharacterAttack") == true)
{
Speed = 0.0f;
}
}
private void Attack()
{
//The trigger for the animator that kick the attack animation.
Animator.SetTrigger("Attack");
}
private void FixedUpdate()
{
Rigidbody2D.velocity = new Vector2(Horizontal * Speed, Rigidbody2D.velocity.y);
}
}
Comment
Your answer
