Unity: PhysX, CharacterController and Animator
Unity's 3D physics is built on NVIDIA PhysX. Almost every idea from this course maps onto it: rigid bodies integrated in a fixed step, a broad phase and narrow phase you configure but never write, an iterative contact solver, sleeping, continuous collision detection, and a kinematic capsule for characters. This lesson is the phrasebook. The C# blocks are real Unity 6 code (they don't run on the site); the C++ blocks are runnable models of what Unity does with them. For the engine itself, see Unity with C#.
Rigidbody: the dynamic body
A Rigidbody component turns a GameObject into a dynamic body; its colliders (BoxCollider, SphereCollider, CapsuleCollider, MeshCollider) give it shape. Unity 6 renamed a few properties, so older tutorials use names that are now obsolete:
| Concept (this course) | Unity 6 | Older name |
|---|---|---|
| linear velocity | rb.linearVelocity |
velocity |
| angular velocity (rad/s) | rb.angularVelocity |
|
| linear / angular damping | rb.linearDamping, rb.angularDamping |
drag, angularDrag |
| kinematic body | rb.isKinematic = true + MovePosition / MoveRotation |
|
| render interpolation | rb.interpolation = RigidbodyInterpolation.Interpolate |
|
| CCD | rb.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic |
|
| sleeping | rb.sleepThreshold, Sleep(), WakeUp(), IsSleeping() |
|
| max push-out speed | rb.maxDepenetrationVelocity |
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(Rigidbody))]
public class Hovercraft : MonoBehaviour
{
[SerializeField] float thrust = 12f;
[SerializeField] float maxSpeed = 8f;
[SerializeField] InputActionReference throttleAction; // a 1D axis action (W/S, left stick Y)
Rigidbody rb;
float throttle; // read in Update, applied in FixedUpdate
void Awake()
{
rb = GetComponent<Rigidbody>();
rb.interpolation = RigidbodyInterpolation.Interpolate; // smooth rendering between steps
rb.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
}
void Update() => throttle = throttleAction.action.ReadValue<float>();
void FixedUpdate()
{
rb.AddForce(transform.forward * thrust * throttle, ForceMode.Force);
if (rb.linearVelocity.magnitude > maxSpeed)
rb.linearVelocity = rb.linearVelocity.normalized * maxSpeed;
}
}Note: Input is read in
Update(every rendered frame) and only stored; the force is applied inFixedUpdate. The example uses the Input System package; enable the action (or use aPlayerInputcomponent) before reading it.
ForceMode is just "how to change velocity"
AddForce takes a ForceMode that says whether the vector is a force or an impulse, and whether mass matters. Each one is a different one-line change to velocity in the next step, which is easy to check:
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::fixed << std::setprecision(3);
const double mass = 2.0, dt = 0.02, value = 10.0; // Unity's default fixed step is 0.02 s
struct Mode { const char* name; double dv; };
Mode modes[] = {
{"Force (F * dt / m)", value * dt / mass},
{"Acceleration (a * dt) ", value * dt},
{"Impulse (J / m) ", value / mass},
{"VelocityChange (dv) ", value},
};
for (const Mode& m : modes)
std::cout << m.name << " -> velocity change " << m.dv << " m/s per call\n";
}Force (F * dt / m) -> velocity change 0.100 m/s per call
Acceleration (a * dt) -> velocity change 0.200 m/s per call
Impulse (J / m) -> velocity change 5.000 m/s per call
VelocityChange (dv) -> velocity change 10.000 m/s per call
So: continuous pushes (thrusters, wind) use Force or Acceleration every FixedUpdate; one-off kicks (a jump, an explosion, a bullet hit) use Impulse or VelocityChange once. Calling Impulse every frame is a classic "my rocket goes to orbit" bug.
FixedUpdate and interpolation
Unity runs FixedUpdate and the physics step zero or more times per rendered frame, every Time.fixedDeltaTime seconds (0.02 s by default, set in Project Settings > Time). That is the accumulator loop from Fixed Timestep and Interpolation. With Interpolate, the Transform you see is blended between the previous and the current physics pose. Here is that loop with uneven frame times and a falling body:
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::fixed << std::setprecision(3);
const double fixedDt = 0.02, g = -9.81;
double y = 10, vy = 0, prevY = 10, acc = 0;
const double frames[] = {0.016, 0.016, 0.033, 0.008, 0.016, 0.050};
for (int f = 0; f < 6; f++) {
acc += frames[f];
int steps = 0;
while (acc >= fixedDt - 1e-12) { // FixedUpdate + physics step
prevY = y;
vy += g * fixedDt;
y += vy * fixedDt;
acc -= fixedDt;
steps++;
}
double alpha = acc / fixedDt;
double shown = prevY + (y - prevY) * alpha; // RigidbodyInterpolation.Interpolate
std::cout << "frame " << f << " dt " << frames[f] << ": " << steps << " step(s), physics y "
<< y << ", rendered y " << shown << "\n";
}
}frame 0 dt 0.016: 0 step(s), physics y 10.000, rendered y 10.000
frame 1 dt 0.016: 1 step(s), physics y 9.996, rendered y 9.998
frame 2 dt 0.033: 2 step(s), physics y 9.976, rendered y 9.985
frame 3 dt 0.008: 0 step(s), physics y 9.976, rendered y 9.981
frame 4 dt 0.016: 1 step(s), physics y 9.961, rendered y 9.969
frame 5 dt 0.050: 2 step(s), physics y 9.918, rendered y 9.919
Frames 0 and 3 run no physics step at all, and frame 2 runs two. Without interpolation the rendered position would freeze on frame 3 and jump on frame 4: that is the "jittery Rigidbody camera" every Unity developer meets once. The rendered value always trails the simulation by less than one step, which is the price of smoothness.
Rules that follow from the loop:
- Apply forces and set velocities in
FixedUpdate; read input inUpdateand store it (anaction.WasPressedThisFrame()check insideFixedUpdatecan miss presses on frames with zero steps, or see one twice on frames with two). - Move kinematic bodies with
rb.MovePosition/MoveRotationinFixedUpdate, not by writingtransform.position, so contacts and interpolation stay correct. Physics.simulationModecan switch the step toUpdateor to manualPhysics.Simulate(dt)calls (SimulationMode.Script), useful for replays and prediction.
CharacterController: the kinematic capsule
CharacterController is the collide-and-slide controller from Collide and Slide, implemented inside PhysX. It is not a Rigidbody: gravity, jumping and pushing are your code.
| Property | Meaning |
|---|---|
slopeLimit |
steepest walkable slope, degrees |
stepOffset |
highest step it climbs, meters |
skinWidth |
contact offset that keeps the capsule from sticking |
minMoveDistance |
moves shorter than this are ignored |
isGrounded |
touched the ground during the last Move |
collisionFlags |
Below, Sides, Above from the last Move |
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class Mover : MonoBehaviour
{
[SerializeField] float speed = 5f, jumpHeight = 1.2f, gravity = -20f;
CharacterController cc;
Vector3 velocity;
void Awake() => cc = GetComponent<CharacterController>();
public void Tick(Vector2 move, bool jump, float dt)
{
if (cc.isGrounded && velocity.y < 0f) velocity.y = -2f; // keep pressing into the ground
if (cc.isGrounded && jump) velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
velocity.y += gravity * dt;
Vector3 horizontal = transform.right * move.x + transform.forward * move.y;
cc.Move((horizontal * speed + Vector3.up * velocity.y) * dt);
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
if (hit.rigidbody != null && !hit.rigidbody.isKinematic) // push crates
hit.rigidbody.AddForce(hit.moveDirection * 2f, ForceMode.Impulse);
}
}The small negative velocity.y on the ground is a cheap form of ground snapping: without it, walking down a slope makes isGrounded flicker because the capsule briefly leaves the surface.
Animator and Animation Rigging
The Animator runs an Animator Controller: state machines, blend trees, layers and avatar masks (Blend Trees, Root Motion and Events).
static readonly int SpeedId = Animator.StringToHash("Speed");
static readonly int JumpId = Animator.StringToHash("Jump");
animator.SetFloat(SpeedId, horizontalSpeed, 0.1f, Time.deltaTime); // damped parameter for a 1D blend tree
if (jumped) animator.SetTrigger(JumpId);
void OnAnimatorMove() // root motion: the clip moves the capsule
{
cc.Move(animator.deltaPosition);
transform.rotation *= animator.deltaRotation;
}animator.applyRootMotionturns root motion on; definingOnAnimatorMovelets you route it yourself (into aCharacterControllerorrb.MovePosition).animator.updateMode = AnimatorUpdateMode.Fixedsteps the Animator with physics; use it when animation drives rigid bodies. The other modes areNormalandUnscaledTime(for menus during a pause).- Animation events are added to clips in the Animation window and call a public method with that name on a component of the Animator's GameObject: footstep sounds, hit frames, VFX.
- The Animation Rigging package (
com.unity.animation.rigging) adds runtime constraints on top of clips: aRigBuilderon the Animator, aRigchild with a weight, and constraints such asTwoBoneIKConstraint(root, mid, tip, target: the solver from Two-Bone IK) andMultiAimConstraint(head look-at). Blend a constraint in and out with itsweight.
Tip: Hand IK to Animation Rigging for feet on slopes: raycast down from each foot in
FixedUpdate, move the IK target to the hit point, and fadeweightto 0 while the foot is in the air.
Test yourself
Which Unity 6 property replaces Rigidbody.velocity?
rb.speedrb.linearVelocityrb.velocity3Drb.moveVelocity
A rocket uses AddForce(up * 50, ForceMode.Impulse) inside FixedUpdate. What goes wrong?
- Nothing
- It applies a full impulse every physics step, so it accelerates absurdly fast
- Impulses are ignored in FixedUpdate
- It only works on kinematic bodies
Why can a Rigidbody look jittery when the camera follows it without interpolation?
- PhysX is imprecise
- Some rendered frames run zero physics steps and others run two, so the visible position moves unevenly
- Interpolation slows physics
- FixedUpdate runs every frame