Here's a rigidbody character controller in Unity that uses root motion for movement:
Character Controller Script
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(Animator))]
public class RootMotionCharacterController : MonoBehaviour
{
[Header("Movement Settings")]
public float walkSpeed = 2f;
public float runSpeed = 5f;
public float rotationSpeed = 10f;
public float groundCheckDistance = 0.1f;
[Header("Ground Detection")]
public LayerMask groundMask = 1;
public Transform groundCheck;
private Rigidbody rb;
private Animator animator;
private Vector3 rootMotionVelocity;
private bool isGrounded;
// Input variables
private Vector2 inputVector;
private bool isRunning;
// Animation parameter hashes for performance
private int speedHash = Animator.StringToHash("Speed");
private int isRunningHash = Animator.StringToHash("IsRunning");
private int isGroundedHash = Animator.StringToHash("IsGrounded");
void Start()
{
rb = GetComponent<Rigidbody>();
animator = GetComponent<Animator>();
// Configure rigidbody
rb.freezeRotation = true; // Prevent physics rotation
// If no ground check transform is assigned, create one
if (groundCheck == null)
{
GameObject groundCheckObj = new GameObject("GroundCheck");
groundCheckObj.transform.SetParent(transform);
groundCheckObj.transform.localPosition = Vector3.down * 1f;
groundCheck = groundCheckObj.transform;
}
}
void Update()
{
HandleInput();
CheckGrounded();
UpdateAnimator();
}
void FixedUpdate()
{
ApplyRootMotion();
ApplyRotation();
}
void HandleInput()
{
// Get input from keyboard/gamepad
inputVector.x = Input.GetAxis("Horizontal");
inputVector.y = Input.GetAxis("Vertical");
// Check for run input
isRunning = Input.GetKey(KeyCode.LeftShift);
}
void CheckGrounded()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundCheckDistance, groundMask);
}
void UpdateAnimator()
{
// Calculate movement speed based on input magnitude
float speed = inputVector.magnitude;
// Adjust speed based on whether we're running
if (isRunning && speed > 0)
{
speed = Mathf.Lerp(speed, runSpeed / walkSpeed, Time.deltaTime * 5f);
}
// Set animator parameters
animator.SetFloat(speedHash, speed);
animator.SetBool(isRunningHash, isRunning && inputVector.magnitude > 0.1f);
animator.SetBool(isGroundedHash, isGrounded);
}
void ApplyRootMotion()
{
if (!isGrounded) return;
// Get the root motion velocity from the animator
Vector3 rootMotion = animator.deltaPosition;
// Apply input direction to root motion
if (inputVector.magnitude > 0.1f)
{
// Calculate movement direction relative to camera or world
Vector3 moveDirection = new Vector3(inputVector.x, 0, inputVector.y).normalized;
// If you want camera-relative movement, uncomment these lines:
// Camera cam = Camera.main;
// if (cam != null)
// {
// Vector3 forward = cam.transform.forward;
// Vector3 right = cam.transform.right;
// forward.y = 0;
// right.y = 0;
// moveDirection = (forward * inputVector.y + right * inputVector.x).normalized;
// }
// Scale root motion by input magnitude and speed
float speedMultiplier = isRunning ? runSpeed : walkSpeed;
rootMotion = moveDirection * animator.deltaPosition.magnitude * speedMultiplier;
}
else
{
rootMotion = Vector3.zero;
}
// Apply root motion to rigidbody
rb.MovePosition(rb.position + rootMotion);
}
void ApplyRotation()
{
if (inputVector.magnitude > 0.1f && isGrounded)
{
// Calculate target rotation based on movement direction
Vector3 moveDirection = new Vector3(inputVector.x, 0, inputVector.y).normalized;
// For camera-relative rotation, use the same camera calculation as above
Quaternion targetRotation = Quaternion.LookRotation(moveDirection);
// Smoothly rotate towards target
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation,
rotationSpeed * Time.fixedDeltaTime);
}
}
// This method is called by the Animator to apply root motion
void OnAnimatorMove()
{
// Store the root motion for use in FixedUpdate
rootMotionVelocity = animator.deltaPosition / Time.fixedDeltaTime;
}
void OnDrawGizmosSelected()
{
// Draw ground check sphere
if (groundCheck != null)
{
Gizmos.color = isGrounded ? Color.green : Color.red;
Gizmos.DrawWireSphere(groundCheck.position, groundCheckDistance);
}
}
}
Setup Instructions
-
Animator Setup: Create an Animator Controller with these parameters:
Speed (Float): Controls movement speed
IsRunning (Bool): Determines if character is running
IsGrounded (Bool): Ground state for jump/fall animations
-
Animation States: Set up blend trees or states for:
- Idle animation
- Walk cycle with root motion
- Run cycle with root motion
- Jump/fall animations (optional)
-
Rigidbody Configuration:
- Mass: 1
- Drag: 0
- Angular Drag: 0
- Freeze Rotation: X, Z (Y rotation handled by script)
-
Collider: Add a CapsuleCollider that fits your character
-
Ground Layer: Create a "Ground" layer and assign it to your ground objects, then set the groundMask in the script
Key Features
- Root Motion Integration: Uses
OnAnimatorMove() to capture root motion from animations
- Physics-Based: Uses
Rigidbody.MovePosition() for smooth, physics-compliant movement
- Ground Detection: Reliable ground checking for proper animation states
- Input Handling: Supports keyboard/gamepad input with run modifier
- Smooth Rotation: Character rotates smoothly toward movement direction
- Performance Optimized: Uses animation parameter hashes for better performance
The script handles the integration between Unity's animation system and physics, ensuring your character moves naturally while respecting collision and physics interactions.