Search Unity

Question Walking animation won't work but idle directions will?

Discussion in '2D' started by Sammyueru1, Mar 30, 2021.

  1. Sammyueru1

    Sammyueru1

    Joined:
    Jul 20, 2020
    Posts:
    45
    So I already put this on reddit but no one replied soon enough so I thought I would put this here:

    Alright so I set up a game with movement and got it all to work idle directions, walking, collisions, etc. except for the walking animation which I set up but it won't switch to the moving animation even though the script seems to be good

    Player Movement + Player Animation Script:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMovement : MonoBehaviour
    6. {
    7.     [Header("Player Speed")]
    8.     public float speed = 4f;
    9.  
    10.     [Header("Starting Direction Variables")]
    11.     public float startRotationX = 0f;
    12.     public float startRotationY = -1f;
    13.  
    14.     private Rigidbody2D myRigidBody;
    15.     private Vector3 change;
    16.     private Animator animator;
    17.  
    18.  
    19.     void Start()
    20.     {
    21.         animator = GetComponent<Animator>();
    22.         myRigidBody = GetComponent<Rigidbody2D>();
    23.         animator.SetFloat("moveX", startRotationX);
    24.         animator.SetFloat("moveY", startRotationY);
    25.     }
    26.  
    27.     void FixedUpdate()
    28.     {
    29.         change = Vector3.zero;
    30.         change.x = Input.GetAxisRaw("Horizontal");
    31.         change.y = Input.GetAxisRaw("Vertical");
    32.         UpdateAnimationAndMove();
    33.     }
    34.  
    35.     void UpdateAnimationAndMove()
    36.     {
    37.         if(change != Vector3.zero)
    38.         {
    39.             MoveCharacter();
    40.             animator.SetFloat("moveX", change.x);
    41.             animator.SetFloat("moveY", change.y);
    42.             animator.SetBool("moving", true);
    43.         }
    44.         else
    45.         {
    46.             animator.SetBool("moving", false);
    47.         }
    48.     }
    49.  
    50.     void MoveCharacter()
    51.     {
    52.         myRigidBody.MovePosition(
    53.             transform.position + change * speed * Time.fixedDeltaTime
    54.         );
    55.     }
    56. }
    57.  
    The animation stuff:



    If you need anymore information please just ask.
    Thanks in advance!