Hello There!
I am currently working on a top down 3D Controller, where the Player is able to normally move, aim in and move while being rotated to where the mouse is. But now, ive run into an issue. I am trying to use 8 Animations (Forward, Backward, Left, Right and the diagonals) to make it look better. for example when hes rotated to where the mouse is, the animation respective to the direction and movement is used. but i cant seem to figure out what values to use for this. it never completely works. The best ive gotten to was where the animations were right in one direction, but wrong in the opposite.
The script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float moveSpeed = 5f;
[SerializeField] private float rotationSpeed = 10f;
[SerializeField] private float aimMoveSpeed = 3f;
private Rigidbody rb;
private Animator animator;
private Vector2 movementInput;
private bool isAiming;
private float turnSmoothVelocity;
private void Start()
{
rb = GetComponent<Rigidbody>();
animator = GetComponent<Animator>();
}
private void Update()
{
HandleMovement();
UpdateAnimator();
}
public void OnMove(InputAction.CallbackContext context)
{
movementInput = context.ReadValue<Vector2>();
}
public void OnAim(InputAction.CallbackContext context)
{
if (context.started)
{
isAiming = true;
}
else if (context.canceled)
{
isAiming = false;
}
}
private void HandleMovement()
{
Vector3 movement = new Vector3(movementInput.x, 0f, movementInput.y).normalized;
float currentMoveSpeed = isAiming ? aimMoveSpeed : moveSpeed;
if (movement.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(movement.x, movement.z) * Mathf.Rad2Deg + Camera.main.transform.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, 0.1f, rotationSpeed);
rb.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
rb.velocity = moveDirection * currentMoveSpeed;
if (!isAiming)
{
// Smooth rotation towards movement direction when not aiming
Quaternion targetRotation = Quaternion.LookRotation(moveDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * rotationSpeed);
}
}
else
{
rb.velocity = Vector3.zero;
}
if (isAiming)
{
RotateTowardsMouse();
}
}
private void RotateTowardsMouse()
{
Ray ray = Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue());
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
Vector3 lookAtPoint = new Vector3(hit.point.x, transform.position.y, hit.point.z);
transform.LookAt(lookAtPoint);
}
}
private void UpdateAnimator()
{
float moveSpeedNormalized = movementInput.magnitude;
animator.SetFloat("Speed", moveSpeedNormalized);
}
}
The Blend Tree setup:
Thank you for your help!