Posted April 28, 2025 by Goutamraj
#Animations
Player Movement Animations added. Let's discuss the implementation.
The Player Animation Controller script manages player animations based on input movements. It ensures smooth transitions and accurate alignment of the character's animations with the direction of movement.
Key Features
Dynamic Animation Updates: Animations adjust dynamically based on the player's movement input.
Local Space Movement Calculation: Translates 2D input into 3D space for precise animation control.
Animator Integration: Interacts seamlessly with Unity's Animator to manage animation parameters.
1. Variables
animator: A reference to the Animator component responsible for controlling animations.
2. Update Method
Calls CalculateAnimation each frame to update the animation parameters based on player input.
3. CalculateAnimation Method
Converts the 2D movement vector (Vector2) to a 3D vector (Vector3).
Computes local space movement using the dot product to determine the forward/backward and left/right movement.
Updates the animator's AxisZ and AxisX parameters to reflect movement direction and magnitude.
using UnityEngine; public class PlayerAnimationController : MonoBehaviour { [SerializeField] Animator animator; private void Update() { CalculateAnimation(PlayerInputsHandler.moveVector); } public void CalculateAnimation(Vector2 moveInput) { // Convert moveInput to a 3D vector (y = 0) Vector3 input3D = new Vector3(moveInput.x, 0, moveInput.y); // Calculate local space movement float forwardDot = Vector3.Dot(input3D, transform.forward); // Forward/backward float rightDot = Vector3.Dot(input3D, transform.right); // Right/left // Set animator parameters animator.SetFloat("AxisZ", forwardDot); // Y for forward/backward animator.SetFloat("AxisX", rightDot); // X for left/right } }
The Animator Controller for the PlayerAnimationController uses a Blend Tree for smooth transitions between movement animations.
Blend Tree Parameters:
AxisX
: Controls left-right movement.
AxisZ
: Controls forward-backward movement.
The Blend Tree connects to five primary states:
Idle1: Player remains stationary.
RunForward1: Player moves forward.
RunBackward1: Player moves backward.
RunRight1: Player moves to the right.
RunLeft1: Player moves to the left.
Input Mapping:
AxisX
and AxisZ
values from the CalculateAnimation
method directly influence the Blend Tree to transition between states.
Example: A positive AxisZ
value transitions to the RunForward1 state.