using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public float rotationSpeed = 10f;
private Rigidbody rb;
private Animator animator;
void Start()
{
rb = GetComponent<Rigidbody>();
animator = GetComponent<Animator>();
}
void Update()
{
// Handle animations in Update
float moveX = Input.GetAxis("Horizontal");
animator.SetFloat("Speed", Mathf.Abs(moveX * moveSpeed)); // Ensure Speed is a positive value
animator.SetBool("Grounded", true); // Assuming the player is always grounded in this example
}
void FixedUpdate()
{
// Handle physics in FixedUpdate
float moveX = Input.GetAxis("Horizontal") * moveSpeed * Time.fixedDeltaTime;
// Move the player only on the x-axis
Vector3 newPosition = rb.position + new Vector3(moveX, 0f, 0f);
rb.MovePosition(newPosition);
// Rotate to face the direction of movement
if (moveX != 0)
{
Vector3 targetDirection = new Vector3(moveX, 0f, 0f);
Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
rb.rotation = Quaternion.Slerp(rb.rotation, targetRotation, rotationSpeed * Time.fixedDeltaTime);
}
}
}
screenshot showing when i press the A key to the left.
and when moving to the right it’s fine:
screenshot of the player settings in the inspector:
and the animator controller of the player with the blend tree and parameters settings: