Stop movement while attacking

Hi, I just started Unity and have no experience in programming. Just dived into it like an idiot. Anyway, I would appreciate any help on this. I would like for my character to attack when I press a certain button ( keyboard “C” or xbox360 “A”). When I press the key, I want the character to stop moving (if it is moving) and run the animation, wait until the animation stop, then allow the character to move again. I place an animation event at the end of the animation to trigger the PlayerAttackEnds() function.


The animation runs fine until the end but I can’t seem to stop the character movement while it is attacking. How can I do it? And which is better for me to try to do?


A. Add into the attack function someway for it to wait the duration of the animation then continue or


B. Use the animation event to trigger a function to end it (what I’m using right now)

    void Update()
    {
    float moveVertical = Input.GetAxis("Vertical");
    float moveHorizontal = Input.GetAxis("Horizontal");
    movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
    movement = Vector3.ClampMagnitude(movement, 1);
    }

    public void PlayerMovementUsingRigidbody(Vector3 movement)...

    public void PlayerAttack()
    {
        Debug.Log(anim.GetBool("attack"));
        if (Input.GetKey(KeyCode.C) == true | Input.GetButton("Fire1") == true) 
        {
            anim.SetBool("attack", true);
            if (anim.GetBool("attack") == true)
                {
                    movement = Vector3.zero;
                }
        }
        /*else
        {
            //anim.SetBool("attack", false);
            
        }
        */
    } 

    public void PlayerAttackEnds()
    {
        anim.SetBool("attack", false);
    }

Hi

Try to help you, I’m a beginner as you are :slight_smile:

Have you tried to set another boolean for transition between attack and move animations?
Something like “moving” and set it to false while attacking then true again while attack is ended.
Also, if there is an input for moving I suggest to place a “canMove” bool in the script

if(Input......)
{ 
     if (canMove) 
     {
          //movement
          anim.SetBool("moving",true);
     }
}

if (Input.GetKey(KeyCode.C) == true | Input.GetButton("Fire1") == true)   //==true not necessary
         {
             anim.SetBool("attack", true);

             if (anim.GetBool("attack") == true)   //==true not necessary
                 {
                     anim.SetBool("moving", false);
                     canMove=false;
                 }
               else
                { 
                      canMove=true;
                 }
         }