Here's a complete rigidbody character controller that uses root motion in Unity3D:
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(Animator))]
[RequireComponent(typeof(CapsuleCollider))]
public class RootMotionRigidbodyController : MonoBehaviour
{
[Header("Movement Settings")]
[SerializeField] private float moveSpeed = 5f;
[SerializeField] private float rotationSpeed = 10f;
[SerializeField] private float jumpForce = 8f;
[Header("Ground Detection")]
[SerializeField] private LayerMask groundLayers = -1;
[SerializeField] private float groundCheckDistance = 0.1f;
[SerializeField] private float groundCheckRadius = 0.3f;
private Rigidbody rb;
private Animator animator;
private CapsuleCollider capsuleCollider;
private Vector3 rootMotionDelta;
private Quaternion rootMotionRotation;
private Vector3 inputVector;
private bool isGrounded;
private bool jumpRequested;
// Animation parameter hashes for performance
private readonly int moveSpeedHash = Animator.StringToHash("MoveSpeed");
private readonly int isGroundedHash = Animator.StringToHash("IsGrounded");
private readonly int jumpHash = Animator.StringToHash("Jump");
private readonly int verticalVelocityHash = Animator.StringToHash("VerticalVelocity");
void Start()
{
rb = GetComponent<Rigidbody>();
animator = GetComponent<Animator>();
capsuleCollider = GetComponent<CapsuleCollider>();
// Configure rigidbody for character movement
rb.freezeRotation = true;
rb.useGravity = true;
rb.interpolation = RigidbodyInterpolation.Interpolate;
rb.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
}
void Update()
{
// Gather input
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
inputVector = new Vector3(horizontal, 0f, vertical).normalized;
// Jump input
if (Input.GetButtonDown("Jump") && isGrounded)
{
jumpRequested = true;
}
// Update animator parameters
float currentSpeed = inputVector.magnitude * moveSpeed;
animator.SetFloat(moveSpeedHash, currentSpeed);
animator.SetBool(isGroundedHash, isGrounded);
animator.SetFloat(verticalVelocityHash, rb.velocity.y);
if (jumpRequested)
{
animator.SetTrigger(jumpHash);
}
}
void FixedUpdate()
{
CheckGrounded();
ApplyRootMotion();
HandleJump();
HandleRotation();
}
void CheckGrounded()
{
// Spherecast from the bottom of the capsule
Vector3 spherePosition = transform.position + Vector3.up * groundCheckRadius;
isGrounded = Physics.SphereCast(
spherePosition,
groundCheckRadius,
Vector3.down,
out RaycastHit hit,
groundCheckDistance + groundCheckRadius,
groundLayers
);
}
void ApplyRootMotion()
{
// Apply root motion delta to rigidbody
if (rootMotionDelta != Vector3.zero)
{
Vector3 velocity = rootMotionDelta / Time.fixedDeltaTime;
// Preserve vertical velocity for gravity
velocity.y = rb.velocity.y;
// Apply additional input-based movement if needed
if (inputVector.magnitude > 0.1f && rootMotionDelta.magnitude < 0.01f)
{
// Fallback movement when no root motion is available
Vector3 moveDirection = transform.TransformDirection(inputVector);
velocity.x = moveDirection.x * moveSpeed;
velocity.z = moveDirection.z * moveSpeed;
}
rb.velocity = velocity;
rootMotionDelta = Vector3.zero;
}
// Apply root motion rotation
if (rootMotionRotation != Quaternion.identity)
{
rb.MoveRotation(rb.rotation * rootMotionRotation);
rootMotionRotation = Quaternion.identity;
}
}
void HandleJump()
{
if (jumpRequested && isGrounded)
{
rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
jumpRequested = false;
}
}
void HandleRotation()
{
// Rotate character based on input direction
if (inputVector.magnitude > 0.1f)
{
Vector3 lookDirection = new Vector3(inputVector.x, 0f, inputVector.z);
Quaternion targetRotation = Quaternion.LookRotation(lookDirection, Vector3.up);
rb.MoveRotation(Quaternion.Slerp(rb.rotation, targetRotation, rotationSpeed * Time.fixedDeltaTime));
}
}
// Called by Unity's animation system
void OnAnimatorMove()
{
if (Time.deltaTime > 0)
{
rootMotionDelta += animator.deltaPosition;
rootMotionRotation *= animator.deltaRotation;
}
}
// Optional: Add slope handling
bool IsOnSlope(out float slopeAngle)
{
slopeAngle = 0f;
if (Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, capsuleCollider.height / 2f + 0.3f, groundLayers))
{
slopeAngle = Vector3.Angle(Vector3.up, hit.normal);
return slopeAngle > 0f && slopeAngle < 45f; // Adjust max slope angle as needed
}
return false;
}
// Debug visualization
void OnDrawGizmosSelected()
{
Vector3 spherePosition = transform.position + Vector3.up * groundCheckRadius;
Gizmos.color = isGrounded ? Color.green : Color.red;
Gizmos.DrawWireSphere(spherePosition - Vector3.up * groundCheckDistance, groundCheckRadius);
}
}
To use this controller effectively, you'll need to set up your character properly. First, ensure your character model has animations with root motion enabled. In the Animation Import Settings, check "Apply Root Motion" for animations that should drive character movement.
Create an Animator Controller with the following parameters: "MoveSpeed" (Float), "IsGrounded" (Bool), "Jump" (Trigger), and "VerticalVelocity" (Float). Set up your animation states and transitions using these parameters to blend between idle, walk, run, and jump animations.
The script handles several important aspects of character movement. Root motion from animations is captured in OnAnimatorMove() and applied to the rigidbody in FixedUpdate(), ensuring smooth physics-based movement. The controller preserves vertical velocity for proper gravity behavior while applying horizontal movement from root motion. Ground detection uses a spherecast for reliable collision detection on various terrain types.
For additional features, you might want to add slope detection and adjustment, which I've included as an optional method. You can also extend the controller with features like crouching, sliding, or wall jumping by adding appropriate animation states and input handling.
Remember to adjust the movement settings in the inspector to match your character's scale and desired feel. The ground check distance and radius should be tuned based on your character's collider size. Layer masks should be configured to only check against appropriate ground surfaces.
This implementation provides a solid foundation for a physics-based character controller that respects both player input and animation-driven movement, creating natural and responsive character control.