- Home /
How to lock 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. The "Speed" variable is the one I use to indicate movement.
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);
}
}
I don't think a while or loop is appropriate for that. It would get stuck in the loop, would have to use an coroutine probably. An better way would be to use a bool. Declare bool isAttacking; then in Attack() put isAttacking=true; then you can have if(Animator.GetCurrentAnimatorStateInfo(0).IsName("CharacterAttack") == false) isAttacking=false; or you could even do isAttacking=Animator.GetCurrentAnimatorStateInfo(0).IsName("CharacterAttack") to shorten the whole thing and use that line to set the bool to true or false rather than add lines to Attack(). Another method would be to set variables in your animator.
Answer by swanne · Oct 11, 2021 at 02:37 PM
You could wrap your movement code in an IF statement. Declare a bool of canMove and default it to true.
private void FixedUpdate()
{
if(canMove)
{
Rigidbody2D.velocity = new Vector2(Horizontal * Speed, Rigidbody2D.velocity.y);
}
}
Then use a coroutine to handle the logic flow of canMove = Fasle, trigger attack animation and then set canMove back to true again.
Answer by RedRightHand- · Oct 12, 2021 at 04:13 PM
Thank you both! Your answers really helped me. For now, I managed to achive this using this code:
private void Update()
{
if(Animator.GetCurrentAnimatorStateInfo(0).IsName("Attack"))
{
Speed = 0.0f;
} else {
Speed = 3.5f;
}