Monday, May 20, 2024
HomeGame DevelopmentI tried to make movement with animation on unity and had this

I tried to make movement with animation on unity and had this


using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;


public class PlayerMovement : MonoBehaviour
{

    private CharacterController _charactercontroller;
    [SerializeField] private Vector3 _walkDirection;
    [SerializeField] private Vector3 _velocity;
    [SerializeField] private float _speed;
    Animator animator;

    int isWalkingHash;
    int isRunningHash;

    PlayerInput input;

    Vector2 currentMovement;
    bool movementPressed;
    bool runPressed;

    void Awake()
    {
        input = new PlayerInput();

        input.CharacterControls.Movement.performed += ctx =>
        {
            currentMovement = ctx.ReadValue<Vector2>();
            movementPressed = currentMovement.x != 0 || currentMovement.y != 0;
        };
        
        input.CharacterControls.Run.performed += ctx => runPressed = ctx.ReadValueAsButton();
    }

    void Start()
    {
        animator = GetComponent<Animator>();
        _charactercontroller = GetComponent<CharacterController>();

        isWalkingHash = Animator.StringToHash("isWalking");
        isRunningHash = Animator.StringToHash("isRunning");
    }

    void Update()
    {
        handleMovement();
    }
 
    void handleMovement()
    {
        bool isRunning = animator.GetBool(isRunningHash);
        bool isWalking = animator.GetBool(isWalkingHash);

        if ( movementPressed && isWalking) {
            animator.SetBool(isWalkingHash, true);
        }
        if (!movementPressed && !isWalking)
        {
            animator.SetBool(isWalkingHash, false);
        }
        if((movementPressed && runPressed) && isRunning)
            {
                animator.SetBool(isRunningHash, true);
            }
        if((movementPressed || !runPressed) && isRunning)
            {
                animator.SetBool(isRunningHash, false);
            }
        
    }

    private void OnEnable()
    {
        input.CharacterControls.Enable();
    }

    private void OnDisable()
    {
        input.CharacterControls.Disable();
    }
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments