Search Unity

Question How to get if player is stopped or moving?

Discussion in 'Animation' started by TheOneMiner, Sep 19, 2021.

  1. TheOneMiner

    TheOneMiner

    Joined:
    Jul 7, 2020
    Posts:
    2
    I'm trying to animate my player. I have the animations ready and a script for the animation. The Animation float "speedPercent" is just staying the same. Is it possible to see that if the layer is stopped or moving in the CharacterController script? I tried to follow this video.


    Animation.cs


    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.AI;

    public class Animation : MonoBehaviour
    {
    const float locomationAnimationSmoothTime = .2f;

    NavMeshAgent agent;
    Animator animator;

    // Start is called before the first frame update
    void Start()
    {
    agent = GetComponent<NavMeshAgent>();
    animator = GetComponentInChildren<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
    float speedPercent = agent.velocity.magnitude / agent.speed;
    animator.SetFloat("speedPercent", speedPercent, locomationAnimationSmoothTime, Time.deltaTime);
    }
    }



    Character Controller.cs

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine.EventSystems;
    using UnityEngine;
    using UnityEngine.AI;

    public class CharacterController : MonoBehaviour
    {
    public float Speed;
    NavMeshAgent agent;
    public float isSpeed;

    void Start()
    {
    agent = GetComponent<NavMeshAgent>();
    Speed = agent.speed;
    Cursor.visible = false;
    Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    void Update()
    {
    if (EventSystem.current.IsPointerOverGameObject())
    return;

    PlayerMovement();
    }

    void PlayerMovement()
    {
    float hor = Input.GetAxis("Horizontal");
    float ver = Input.GetAxis("Vertical");
    Vector3 playerMovement = new Vector3(hor, 0f, ver) * Speed * Time.deltaTime;
    transform.Translate(playerMovement, Space.Self);
    }
    }