Hey! I am trying to use the WASD to control the Player, and I meet a problem. I do not know how to match the animation with the move, and do not know how to get the local speed of the player. I did come up a way to make the animation works, but definitely not a good way. Can anybody teach me a better method about this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mover : MonoBehaviour
{
public CharacterController player;
public Transform mainCamera;
public float playerMoveSpeed = 6f;
public float playertrunSnoothTime = 0.1f;
float playertrunSmoothVelocity;
private void Update()
{
MovePlayer();
UpdateAnimator();
}
public void MovePlayer()
{
float playerMoveHorizontal = Input.GetAxisRaw("Horizontal");
float playerMoveVertical = Input.GetAxisRaw("Vertical");
Vector3 playerdirection = new Vector3(playerMoveHorizontal, 0, playerMoveVertical).normalized;
if (playerdirection.magnitude >= 0.1f)
{
float N_targetAngle = Mathf.Atan2(playerdirection.x, playerdirection.z) * Mathf.Rad2Deg+mainCamera.eulerAngles.y;
float N_angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, N_targetAngle, ref playertrunSmoothVelocity, playertrunSnoothTime);
transform.rotation = Quaternion.Euler(0f, N_angle, 0f);
Vector3 N_moveDir = Quaternion.Euler(0f, N_targetAngle, 0f) * Vector3.forward;
player.Move(N_moveDir.normalized * playerMoveSpeed * Time.deltaTime);
}
}
protected void UpdateAnimator()
{
if(Input.GetAxis("Horizontal")!=0 ||Input.GetAxis("Vertical")!=0)
{
Vector3 velocity = GetComponent<CharacterController>().velocity;
Vector3 localVelocity = transform.InverseTransformDirection(velocity);
float speed = localVelocity.z;
GetComponent<Animator>().SetFloat("ForwardSpeed",speed);
}
else
{
GetComponent<Animator>().SetFloat("ForwardSpeed",0);
}
}
}