Physics
Physics makes nodes fall, collide, hang from joints and answer questions such as "what is under this cursor?". It is split into two bricks. org.mass4.turian.physics holds the components, queries and callbacks. org.mass4.turian.physics.bepu is the backend that runs the simulation on BepuPhysics. Install both: with only the first, the components load but nothing moves and every query finds nothing.
Setting up
Add both bricks to the project from Project → Bricks… in Studio, or in Bricks/manifest.json as described in Bricks. The project does not need any code to start. Create a Settings / Physics asset under Assets/Settings only when you want to change the defaults in Simulation settings.
Each game session has one physics world. Loading scenes keeps it; restarting the session starts a fresh one.
Your first falling box
- Add a
RigidbodyComponentand aBoxColliderComponentto a node. It falls. - Add a
BoxColliderComponentto a node without a rigidbody, such as the floor. It is static and stays where it is.
A collider with no rigidbody on its node or any ancestor is static. A collider under a rigidbody belongs to that body, and several colliders under one body form a single compound body.
Bodies and colliders
A RigidbodyComponent puts its node under simulation. Its main properties are:
| Property | Meaning |
|---|---|
Mass |
Kilograms. Values below 0.0001 are raised to that minimum. |
UseGravity, GravityScale |
Whether gravity acts on the body, and how strongly. |
IsKinematic |
Scripts move the body; it pushes dynamic bodies but is not pushed by them. |
LinearDamping, AngularDamping |
Fraction of velocity lost per second. |
CollisionDetectionMode |
Use Continuous for fast bodies that must not pass through thin walls. |
Constraints |
Axes the body may not move along or rotate around. |
AutomaticCenterOfMass, CenterOfMass |
Derive the center of mass from the colliders, or set it by hand. |
LinearVelocity, AngularVelocity |
Read or set the velocity. |
Bodies are moved with methods rather than by writing Node.Position: AddForce(force, mode), AddTorque, AddExplosionForce, MovePosition, MoveRotation, Sleep, WakeUp and IsSleeping(). Bodies that rest for long enough fall asleep and cost almost nothing until something touches them.
Every collider shares these properties: IsTrigger (report overlaps instead of colliding), Center, Material, IncludeLayers and ExcludeLayers. The shapes are:
| Component | Menu |
|---|---|
BoxColliderComponent |
Physics/Box Collider |
SphereColliderComponent |
Physics/Sphere Collider |
CapsuleColliderComponent |
Physics/Capsule Collider |
CylinderColliderComponent |
Physics/Cylinder Collider |
MeshColliderComponent |
Physics/Mesh Collider |
HeightfieldColliderComponent |
Physics/Heightfield Collider |
Mesh colliders work on static and kinematic bodies only. A dynamic body with a concave mesh is skipped with a warning; use primitives or a compound of primitives for moving objects.
A body with several colliders uses one material for all of them.
Pushing a body from code
public sealed class Pusher : Component
{
[InjectService(Optional = true), JsonIgnore]
public PhysicsScene? Physics { get; private set; }
public RigidbodyComponent? Body;
public void Push() => Body?.AddForce(Vector3.UnitY * 10, ForceMode.Impulse);
public Node? Aim(Vector3 origin, Vector3 direction)
{
if (Physics is not null && Physics.Raycast(origin, direction, out var hit, 100f))
{
return hit.Node;
}
return null;
}
}
PhysicsScene is null when the physics bricks are not installed, so scripts treat it as optional. The snippets assume the global usings of the example projects, which include Turian.Engine.Physics.
Materials
A PhysicsMaterial sets how a surface slides and bounces:
| Property | Default | Meaning |
|---|---|---|
DynamicFriction |
0.6 | Friction while sliding. |
StaticFriction |
0.6 | Friction before sliding starts. |
Bounciness |
0 | How much energy a bounce returns. |
FrictionCombine, BounceCombine |
Average |
How two materials combine: Average, Minimum, Multiply or Maximum. |
A collider with no material uses PhysicsSettings.DefaultMaterial, or the built-in values when that is empty.
Bepu has no restitution coefficient. It approximates bounciness with a contact spring, and impacts slower than about 2 m/s do not bounce at all. Use bounciness for effect, not for exact rebound heights.
Joints
Joints connect two bodies, or a body and the world:
| Component | Menu |
|---|---|
FixedJointComponent |
Physics/Fixed Joint |
HingeJointComponent |
Physics/Hinge Joint |
SliderJointComponent |
Physics/Slider Joint |
BallSocketJointComponent |
Physics/Ball Socket Joint |
DistanceJointComponent |
Physics/Distance Joint |
SpringJointComponent |
Physics/Spring Joint |
Hinge and slider joints have motors and limits, and the Scene view shows their anchors and axes through the component gizmos.
Character controllers
CharacterControllerComponent (Physics/Character Controller) moves a capsule through the world without becoming a rigidbody. It handles steps, slopes and moving ground, and it does not push other bodies: games implement pushing themselves. Its defaults are a 45° SlopeLimit, a 0.3 m StepOffset and a 0.3 m GroundSnapDistance.
You supply gravity and jumping. Move takes a world-space displacement for the frame and returns the collision flags; IsGrounded tells you whether the character stands on something.
public sealed class Walker : Component
{
public CharacterControllerComponent? Character;
float vertical;
public override void OnFixedUpdate(float fixedDeltaTime)
{
if (Character is null)
{
return;
}
vertical = Character.IsGrounded ? -0.2f : vertical - 9.81f * fixedDeltaTime;
Character.Move(new Vector3(1, vertical, 0) * fixedDeltaTime);
}
}
SimpleMove(speed, deltaTime) applies gravity for you, which suits walking scripts. Teleport(position) moves the character and clears its grounding and falling state, so use it instead of writing Node.Position when changing stations.
Vehicles
WheelColliderComponent (Physics/Wheel Collider) is a raycast suspension and tyre. It applies its forces to the rigidbody above it and adds no collision shape of its own. Drive the chassis with forces or torque; to draw a tyre, read GetWorldPose each frame and place the mesh there. Wheels touch the ground only through their ray.
Ragdolls
RagdollBuilder turns a posed bone hierarchy into physics proxies: one capsule per bone segment, joined to its parent and limited in swing. The bones keep their hierarchy, and the rig drives them.
var definitions = new List<RagdollBone>
{
new() { Bone = hips, EndBone = chest, MassWeight = 8, Radius = 0.16f },
new() { Bone = chest, EndBone = head, MassWeight = 10, Radius = 0.18f },
};
Rig = RagdollBuilder.Create(model, definitions, new() { TotalMass = 70, SwingLimit = 50 });
RagdollBuilder.FromSkeleton(root, bones) infers the segments from the bones you select, including across helper bones that you skip. RagdollSettings sets TotalMass (70 kg), Radius, TerminalLength, SwingLimit (45°) and StartKinematic (true).
The returned RagdollRig owns the generated nodes and its Parts list. While the rig is kinematic, call SyncFromBones() after your animation has moved the bones. When it is dynamic, call SyncToBones() after the simulation, so the bones follow the physics. SetKinematic(bool) hands the current pose across in either direction, and RestoreBindPose() puts the captured local poses back. Dispose() removes only the nodes the rig generated.
The builder reads posed Node bones, so it works with any skeleton or animation system that places them. It does not import skins or draw skinned meshes.
Queries
PhysicsScene answers queries against the world as it currently stands:
| Method | Finds |
|---|---|
Raycast, RaycastAll |
The nearest collider along a ray, or all of them, nearest first. |
SphereCast, BoxCast, CapsuleCast |
The nearest collider a moving shape meets. |
OverlapSphere, OverlapBox, OverlapCapsule |
The colliders a shape touches. |
CheckSphere, CheckBox |
Whether any collider is touched. |
ComputePenetration |
How far two colliders overlap, and the direction to separate them. |
Every query takes an optional LayerMask and a QueryTriggerInteraction. The default trigger setting follows PhysicsSettings.QueriesHitTriggers, and Ignore skips triggers. A RaycastHit gives Point, Normal, Distance, the Collider, and the Rigidbody and Node it belongs to.
Queries miss when no backend is installed or no session is running. A query that finds nothing returns false or an empty result, so it is safe to call from any script.
A typical explosion finds bodies with an overlap, then pushes each one once:
var pushed = new HashSet<RigidbodyComponent>();
foreach (var collider in Physics?.OverlapSphere(point, radius) ?? [])
{
if (collider.AttachedRigidbody is { IsKinematic: false } body && pushed.Add(body))
{
body.WakeUp();
body.AddExplosionForce(force, point, radius, 1f, ForceMode.Impulse);
}
}
Callbacks
Implement ICollisionHandler to hear about contacts, and ITriggerHandler to hear about overlaps with triggers. A handler receives the callbacks of the colliders on its own node and of the body it belongs to.
| Collision callback | When |
|---|---|
OnCollisionEnter(Collision) |
Two colliders start touching. |
OnCollisionStay(Collision) |
They keep touching during a fixed tick. |
OnCollisionExit(Collision) |
They stop touching. The collision has no contacts. |
Triggers use OnTriggerEnter, OnTriggerStay and OnTriggerExit, each with the other ColliderComponent.
Collision gives you Collider, Rigidbody, Node, ContactCount, Contacts, Impulse and RelativeVelocity. A ContactPoint holds the world Point, the Normal pointing towards the receiving collider, and the Separation.
public sealed class ImpactLogger : Component, ICollisionHandler
{
public void OnCollisionEnter(Collision collision)
{
if (collision.ContactCount > 0)
{
Log.Logger.LogInformation("Hit {Node} at {Point}", collision.Node?.Name, collision.GetContact(0).Point);
}
}
}
Contacts are reported only for bodies that have a handler attached.
Layers
Each node has a physics layer, which decides what collides with what. PhysicsSettings.LayerCollisionMatrix holds one 32-bit mask per layer, and SetLayerCollision(a, b, collide) edits both directions. Changing a node's PhysicsLayer takes effect on the next physics step, including for the colliders under that node. During a session, PhysicsScene.IgnoreLayerCollision(layerA, layerB) changes the matrix without touching the asset.
Simulation settings
Create a Settings / Physics asset to change these. The session reads them when it starts, so edits apply to the next session.
| Setting | Default | Meaning |
|---|---|---|
Gravity |
(0, -9.81, 0) | Acceleration in meters per second squared. |
SolverIterations |
4 | Velocity passes per substep. More makes stacks and joints stiffer. |
Substeps |
4 | Solver substeps per step. More is more stable and costs proportionally more. |
SimulationMode |
FixedUpdate |
When the world advances: FixedUpdate once per fixed tick, Update once per frame, or Script only when your code calls Simulate. |
DefaultMaterial |
none | Material for colliders that set none. |
LayerCollisionMatrix |
all layers collide | The collision matrix described under Layers. |
QueriesHitTriggers |
true | Whether queries report triggers by default. |
SleepThreshold |
0.1 | Speed below which a body counts as calm. |
Multithreaded |
true | Spreads each step over worker threads. |
WorkerThreads |
0 | Worker count for a multithreaded step. Zero uses every logical processor. |
Deterministic |
false | Repeats results on the same machine and inputs, at some cost. It does not make results identical across machines. |
For speed, use fewer SolverIterations and Substeps, and leave Multithreaded on. Fewer iterations make stacks and joints softer, so measure before you change them.
Diagnostics
PhysicsScene.Statistics returns a snapshot of the world and the cost of the last step:
if (Physics is { } physics)
{
var stats = physics.Statistics;
Log.Logger.LogInformation("{Awake} of {Bodies} bodies awake, last step {Step:0.00} ms",
stats.AwakeBodies, stats.Bodies, stats.StepMilliseconds);
}
| Field | Meaning |
|---|---|
Bodies |
Backend bodies, static colliders included. |
StaticBodies, SleepingBodies, AwakeBodies |
How many are static, asleep, or being simulated. |
Joints |
Joints created in the backend. |
ContactPairs |
Collider pairs the last step found touching. Resting pairs of sleeping bodies count only when a handler receives them. |
Steps |
Steps taken since the scene started. |
StepMilliseconds |
The backend's time for the last step. |
SimulateMilliseconds |
The whole last step, including syncing transforms, writing poses back and dispatching callbacks. |
To see colliders and contacts while you work, turn on Gizmos in the Scene view. In Studio, selecting a collider or rigidbody in the running hierarchy shows its gizmos during Play or Pause; the transform handles stay hidden while the session runs. The Gizmos page describes the Scene view controls.
Example project
example-12-physics is the reference for everything on this page. Open it as a project, press Play and press 1 to 9 to switch scenes:
| Scene | Shows |
|---|---|
| Box pile, Box rain | Benchmarks: 1,000 boxes in a pile, or rain up to a chosen count, with sleep and step timings in the Output panel. |
| Tower shooter | Continuous collision for thrown balls, ray picking, dragging a body and explosions. |
| Materials | Friction and bounciness combinations from the table above. |
| Physics lab | Query shapes and masks, triggers, collision callbacks, layer changes, mesh and hull contacts. |
| Controller | Steps, slopes and a moving platform for a character controller. |
| Joints | All six joint types, with motors and limits. |
| Vehicle | Raycast wheels, steering and braking. |
| Ragdoll | A ragdoll fitted to a posed mannequin, switching between animation and physics. |
Its Assets/Scripts folder holds the code for each scene. DemoBodies.cs shows how to spawn and despawn bodies at runtime, and TowerShooter.cs shows picking, dragging and explosions.
Limitations
- Results repeat only on the same machine.
- Heightfields behave as plain static meshes.
- Wheels touch the ground only through their ray.
- Bounciness is an approximation, so bounce heights are not exact; see Materials.
Next steps
- Components — the lifecycle your physics scripts hook into.
- Scenes — loading and switching scenes while the physics world keeps running.
- Bricks — installing the physics bricks.
- Audio — sound for impacts and collisions.