using UnityEngine;
public class RootMotionCharacterController : MonoBehaviour
{
[Header("References")]
public Animator animator;
public Rigidbody rb;
public CapsuleCollider capsuleCollider;
[Header("Movement Settings")]
public float rotationSpeed = 500f;
public float gravity = -9.81f;
public float jumpHeight = 2f;
private Vector3 velocity;
private bool isGrounded;
void Start()
{
if (animator == null)
{
Debug.LogError("Animator not assigned!");
enabled = false;
return;
}
if (rb == null)
{
Debug.LogError("Rigidbody not assigned!");
enabled = false;
return;
}
if (capsuleCollider == null)
{
Debug.LogError("Capsule Collider not assigned!");
enabled = false;
return;
}
// Ensure Rigidbody is set to kinematic. Root motion will handle movement.
rb.isKinematic = true;
}
void Update()
{
// Ground Check
isGrounded = Physics.CheckCapsule(capsuleCollider.bounds.center, capsuleCollider.bounds.center + Vector3.down * capsuleCollider.height / 2, capsuleCollider.radius, LayerMask.GetMask("Ground"));
// Jump
if (isGrounded && Input.GetButtonDown("Jump"))
{
velocity.y = Mathf.Sqrt(jumpHeight * 2f * -gravity);
}
// Rotation (Horizontal Input)
float horizontalInput = Input.GetAxis("Horizontal");
if (horizontalInput != 0)
{
transform.Rotate(Vector3.up, horizontalInput * rotationSpeed * Time.deltaTime);
}
}
void FixedUpdate()
{
// Apply Gravity
velocity.y += gravity * Time.fixedDeltaTime;
// Apply Root Motion
if (animator.applyRootMotion)
{
// Apply the root motion delta position. This is the core of the controller.
rb.MovePosition(rb.position + animator.deltaPosition);
// Apply the root motion delta rotation.
rb.MoveRotation(rb.rotation * animator.deltaRotation);
}
// Apply Vertical Velocity (Jump/Gravity)
Vector3 verticalMovement = velocity * Time.fixedDeltaTime;
rb.MovePosition(rb.position + verticalMovement);
// Reset vertical velocity when grounded to prevent accumulating gravity.
if (isGrounded)
{
velocity.y = -2f; // Small negative value to keep grounded. Avoids floating point issues.
}
}
// Optional: Visualize the ground check
void OnDrawGizmosSelected()
{
if (capsuleCollider != null)
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireCapsule(capsuleCollider.bounds.center, capsuleCollider.bounds.center + Vector3.down * capsuleCollider.height / 2, capsuleCollider.radius);
}
}
}
Key improvements and explanations:
- Rigidbody Kinematic: Crucially, the
Rigidbody is set to isKinematic = true in Start(). This is essential when using root motion. Root motion directly manipulates the transform, and if the Rigidbody is not kinematic, it will fight against the animation. The Rigidbody is still used for collision detection and MovePosition/MoveRotation which are much more robust than directly setting transform.position and transform.rotation.
MovePosition and MoveRotation: Uses Rigidbody.MovePosition and Rigidbody.MoveRotation instead of directly modifying transform.position and transform.rotation. This is critical for proper physics interactions and collision handling. MovePosition and MoveRotation are designed to work with the physics engine and avoid issues like tunneling through colliders.
- Root Motion Application: The core logic is in
FixedUpdate():
rb.MovePosition(rb.position + animator.deltaPosition); applies the root motion's positional change.
rb.MoveRotation(rb.rotation * animator.deltaRotation); applies the root motion's rotational change.
- Ground Check: Uses
Physics.CheckCapsule for a more reliable ground check. This is better than a simple raycast because it accounts for the capsule shape of the character. The LayerMask.GetMask("Ground") ensures that only the "Ground" layer is considered for the ground check. Important: Make sure you have a layer named "Ground" in your Unity project and assign it to your ground objects.
- Jump: Implements a basic jump using
velocity.y. The jump force is calculated based on jumpHeight and gravity.
- Gravity: Applies gravity consistently in
FixedUpdate().
- Rotation: Handles horizontal rotation using
Input.GetAxis("Horizontal") and transform.Rotate.
- Grounded Reset: Resets
velocity.y to a small negative value when grounded to prevent the character from floating due to floating-point inaccuracies.
- Error Handling: Includes basic error checking to ensure that the necessary components (Animator, Rigidbody, CapsuleCollider) are assigned.
- Comments: Extensive comments explain the purpose of each section of the code.
- Visualization: The
OnDrawGizmosSelected() function provides a visual representation of the ground check capsule in the editor, making it easier to debug.
- Clearer Structure: The code is organized into sections with headers for better readability.
How to Use:
- Create a new Unity project (or use an existing one).
- Create a 3D object for your character (e.g., a Capsule).
- Add a
Rigidbody component to the character. Set isKinematic to true in the Inspector.
- Add a
CapsuleCollider component to the character.
- Add an
Animator component to the character.
- Create an Animator Controller. This controller should contain animations with root motion data (e.g., walking, running, jumping). Make sure "Apply Root Motion" is checked on the Animator component.
- Create a new C# script named
RootMotionCharacterController.
- Copy and paste the code above into the script.
- Attach the
RootMotionCharacterController script to your character.
- In the Inspector, assign the
Animator, Rigidbody, and CapsuleCollider components to the corresponding fields in the script.
- Create a ground object (e.g., a Plane or Cube).
- Create a new Layer named "Ground".
- Assign the "Ground" layer to your ground object.
- Test the character movement. Use the horizontal input (A/D or Left/Right arrow keys) to rotate, and the jump button (Spacebar) to jump.
Important Considerations:
- Root Motion Data: The animations you use must have root motion data baked into them. This is usually done in your 3D modeling software (e.g., Blender, Maya, 3ds Max) when creating the animations. In Unity, you can check if an animation has root motion data by selecting the animation clip in the Project window and looking at the Inspector. There should be a section for "Root Motion".
- Animation Events: You can use animation events to trigger additional actions during animations (e.g., playing sounds, spawning particles).
- Collision Handling: The
CapsuleCollider is responsible for collision detection. Make sure your ground and other objects have colliders as well.
- Layer Mask: The
LayerMask is used to filter which objects are considered for the ground check. Make sure your ground objects are on the "Ground" layer.
- Fine-Tuning: You may need to adjust the
rotationSpeed, gravity, and jumpHeight values to achieve the desired movement behavior.
- Slopes: This basic controller doesn't handle slopes perfectly. You might need to add additional logic to handle slopes more gracefully.
- Stairs: Stair climbing is also not handled by this basic controller. You would need to add more complex logic to detect and handle stairs.
- Animation Blending: Smooth animation blending is important for a natural-looking character. Use the Animator Controller to create smooth transitions between animations.
This comprehensive example provides a solid foundation for building a root motion-based character controller in Unity. Remember to adapt and extend it to meet the specific requirements of your game.