Physics

Gorilla3D includes a built-in physics engine for realistic simulation of rigid body dynamics, collision detection, and constraints. The framework supports two physics backends: the built-in Q3 Physics Engine and the JOLT Physics Engine, selectable at design-time or runtime.

Table of Contents

Overview

The physics system (TGorillaPhysicsSystem) is the central component that:

  • Manages rigid bodies and their colliders
  • Runs the physics simulation step
  • Detects collisions and reports contact events
  • Supports joints/constraints between bodies
  • Provides force, impulse, and velocity control
  • Offers design-time collider and joint prefabs
  • Supports debug rendering of colliders

Getting Started

Design-Time

  1. Drop a TGorillaPhysicsSystem onto your viewport
  2. Set Active := True
  3. Set Gravity (default: (0, 9.81, 0) — downward in FMX Y-up)
  4. Add collider prefabs via the Colliders collection in the Object Inspector
  5. Call Step() from a timer (recommended interval: 33ms for ~30 Hz)

Runtime

var
  Physics: TGorillaPhysicsSystem;
begin
  Physics := TGorillaPhysicsSystem.Create(Self);
  Physics.Parent := GorillaViewport1;
  Physics.Driver := TGorillaPhysicsDriverType.Q3Physics;
  Physics.Gravity := Point3D(0, 9.81, 0);
  Physics.Accuracy := 10;
  Physics.Active := True;
end;

// In a timer (33ms interval):
procedure TForm1.Timer1Timer(Sender: TObject);
begin
  GorillaPhysicsSystem1.Step();
end;

Physics Drivers

Driver Enum Value Description
Q3 Physics Q3Physics Built-in lightweight physics engine. Supports the full set of collider shapes (box, sphere, capsule, cylinder, cone, convex hull, mesh, terrain) and joint types.
JOLT Physics JOLTPhysics External high-performance physics engine. Same collider and joint coverage as Q3, tuned for large/complex scenes.
Custom CustomPhysics Register your own physics driver implementation.
Physics.Driver := TGorillaPhysicsDriverType.JOLTPhysics;

Collider Types

Collider Q3 JOLT Method
Box Yes Yes AddBoxCollider
Sphere Yes Yes AddSphereCollider
Capsule Yes Yes AddCapsuleCollider
Cylinder Yes Yes AddCylinderCollider
Cone Yes Yes AddConeCollider
Convex Hull Yes Yes AddConvexHullCollider
Mesh Yes Yes AddMeshCollider (experimental)
Terrain Yes Yes AddTerrainCollider
Particle Yes Yes AddParticleCollider (used internally by particle system)

Collider Settings

Before adding a collider, create a TGorillaColliderSettings record to configure the body:

var
  Settings: TGorillaColliderSettings;
begin
  // Create settings for a dynamic body
  Settings := TGorillaColliderSettings.Create(TGorillaPhysicsBodyType.eDynamicBody);

  // Physics material
  Settings.Data.Friction := 0.4;
  Settings.Data.Restitution := 0.3;  // bounciness
  Settings.Data.Density := 1.0;
  Settings.Data.Sensor := False;      // True = trigger only, no physical response

  // Lock axes
  Settings.LockRotAxisX := False;
  Settings.LockRotAxisY := False;
  Settings.LockRotAxisZ := False;

  // Damping
  Settings.LinearDamping := 0.0;
  Settings.AngularDamping := 0.05;

  // Velocity limits
  Settings.MaxLinearVelocity := Point3D(100, 100, 100);
  Settings.MaxAngularVelocity := Point3D(100, 100, 100);

  // Collision layers (bodies only collide within the same layer)
  Settings.Layers := 1;

  // Sleep optimization
  Settings.AllowSleep := True;
  Settings.Active := True;
end;

Body Types

Type Enum Description
Static eStaticBody Does not move. Use for floors, walls, terrain.
Dynamic eDynamicBody Fully simulated. Responds to forces, gravity, and collisions.
Kinematic eKinematicBody Moved by code, not by physics. Pushes dynamic bodies but is not pushed back.

Adding Colliders

Box Collider

var Settings: TGorillaColliderSettings;
begin
  // Floor (static)
  Settings := TGorillaColliderSettings.Create(eStaticBody);
  Settings.Data.Friction := 0.6;
  GorillaPhysicsSystem1.AddBoxCollider(FloorPlane, Settings);

  // Falling crate (dynamic)
  Settings := TGorillaColliderSettings.Create(eDynamicBody);
  Settings.Data.Restitution := 0.2;
  GorillaPhysicsSystem1.AddBoxCollider(CrateModel, Settings);

  // Custom size override
  GorillaPhysicsSystem1.AddBoxCollider(SomeControl, Settings, Point3D(2, 2, 2));
end;

Sphere Collider

Settings := TGorillaColliderSettings.Create(eDynamicBody);
Settings.Data.Restitution := 0.8; // bouncy ball
GorillaPhysicsSystem1.AddSphereCollider(BallMesh, Settings); // auto-detect radius
GorillaPhysicsSystem1.AddSphereCollider(BallMesh, Settings, 1.5); // explicit radius

Capsule Collider

Settings := TGorillaColliderSettings.Create(eDynamicBody);
Settings.LockRotAxisX := True;
Settings.LockRotAxisZ := True; // keep upright
GorillaPhysicsSystem1.AddCapsuleCollider(CharacterModel, Settings, 0.5, 1.8);

Terrain Collider

Settings := TGorillaColliderSettings.Create(eStaticBody);
GorillaPhysicsSystem1.AddTerrainCollider(GorillaTerrain1, Settings);

Removing Colliders

GorillaPhysicsSystem1.RemoveCollider(CrateModel);

Joints and Constraints

Joints connect two bodies together. Configure them via the Joints collection at design-time or add them programmatically.

Joint Types

Both physics backends now support the full set of joint types. The original eight joints were joined by the JOLT-parity constraints (Point, Distance, Cone, SwingTwist, SixDOF) and the coupling constraints (Gear, RackAndPinion, Pulley) — these are now implemented natively in both the Q3 and the JOLT backend, so a scene behaves the same regardless of the driver.

Joint Description Q3 JOLT
Fixed Locks two bodies together rigidly Yes Yes
BallAndSocket Free rotation around a point (shoulder, hip) Yes Yes
Hinge Rotation on one axis (door, wheel) Yes Yes
LimitedHinge Hinge with angle limits (finger, knee) Yes Yes
Prismatic Sliding on one axis (sliding door, elevator) Yes Yes
StiffSpring Soft spring that maintains a distance between bodies Yes Yes
Magnet Attracts one body toward another based on mass Yes Yes
Buoyancy Simulates floating on a fluid surface Yes Yes
Point Point-to-point pin (equivalent to BallAndSocket) Yes Yes
Distance Keeps two anchors a fixed distance apart (rigid rope) Yes Yes
Cone Pin whose swing is limited to a cone Yes Yes
SwingTwist Swing cone + twist limit (ragdoll joints) Yes Yes
SixDOF Per-axis translation / rotation limits Yes Yes
RackAndPinion Couples a pinion's rotation to a rack's translation Yes Yes
Gear Couples two bodies' rotation (meshed gears) Yes Yes
Pulley Rope of fixed total length over two pulley points Yes Yes

Backend notes

  • Buoyancy is a soft, per-step effect rather than a hard constraint. It uses ControlA as the floating body and ControlB as the fluid-surface anchor. In the Q3 backend it is a spring + damper along the up-axis; in the JOLT backend it is applied through JOLT's native buoyancy, which integrates the actually submerged volume of the body's shape (so it also yields a righting torque). Stiffness/Damping are re-purposed per backend — see the note below.
  • Gear, RackAndPinion and Pulley are coupling constraints: set Ratio (transmission ratio). For Gear/RackAndPinion under JOLT, also wire the two sub-joints (the hinges/slider) via ConstraintA/ConstraintB so JOLT can correct positional drift.
  • For Buoyancy the Stiffness field is the buoyancy strength (Q3) or the buoyancy factor (JOLT: 1 = neutral, > 1 floats, clamped to 2), and Damping is the fluid drag in both backends.

Motor Types

Joints can be motorized:

Motor Description
NoMotor No motor
RotationMotor Constant rotation
AngularVelocityMotor Angular velocity drive
PositionMotor Drive toward a position
LinearVelocityMotor Constant linear velocity
VelocityMotor Combined angular + linear velocity

Buoyancy Example

A Buoyancy joint makes a body float on a fluid. It uses two bodies: ControlA is the floating body, ControlB is a (usually static, invisible) anchor placed at the fluid surface — its height defines where the body floats. The "liquid" itself is normally just a semi-transparent, collider-less volume so the body can actually submerge into it.

var
  LSurface, LFloat: TGorillaCube;
  LJoint: TGorillaPhysicsJointPrefab;
  LSettings: TGorillaColliderSettings;
begin
  // Invisible STATIC anchor at the water surface (y = -5; negative Y = up).
  LSurface := TGorillaCube.Create(Self);
  LSurface.Parent := GorillaViewport1;
  LSurface.SetSize(0.4, 0.1, 0.4);
  LSurface.Position.Point := Point3D(0, -5, 0);
  LSurface.Visible := False;
  LSettings := TGorillaColliderSettings.Create(TGorillaPhysicsBodyType.eStaticBody);
  GorillaPhysicsSystem1.AddBoxCollider(LSurface, LSettings);

  // The floating body (starts submerged; buoyancy lifts it to the surface).
  LFloat := TGorillaCube.Create(Self);
  LFloat.Parent := GorillaViewport1;
  LFloat.SetSize(1.5, 1.5, 1.5);
  LFloat.Position.Point := Point3D(0, -3, 0);
  LSettings := TGorillaColliderSettings.Create(TGorillaPhysicsBodyType.eDynamicBody);
  GorillaPhysicsSystem1.AddBoxCollider(LFloat, LSettings);

  // The buoyancy joint: A = floating body, B = surface anchor.
  LJoint := GorillaPhysicsSystem1.Joints.Add as TGorillaPhysicsJointPrefab;
  LJoint.JointType := TGorillaPhysicsJointType.Buoyancy;
  LJoint.ControlA  := LFloat;      // floating body
  LJoint.ControlB  := LSurface;    // fluid-surface anchor
  LJoint.AnchorA.Point := Point3D(0, 0, 0);
  LJoint.AnchorB.Point := Point3D(0, 0, 0);

  // Stiffness / Damping are interpreted per backend:
  //   Q3   : Stiffness = spring strength (0 -> mass-based default), Damping = drag
  //   JOLT : Stiffness = buoyancy factor (0 -> default 1.2, > 1 floats, max 2),
  //          Damping   = fluid drag
  LJoint.Stiffness := 0;      // 0 -> sensible per-backend default
  LJoint.Damping   := 0.5;
end;

Under JOLT the effect is applied through JOLT's native buoyancy, which integrates the actually submerged volume of the collider shape — so a body pushed under water not only bobs back up but also rights itself if it entered at an angle.

Forces, Impulses and Velocity

Apply physics effects to bodies at runtime:

// Apply an impulse (instant push)
GorillaPhysicsSystem1.RemoteBodyImpulse(CrateModel, Point3D(0, -10, 0));

// Apply a continuous force
GorillaPhysicsSystem1.RemoteBodyForce(CrateModel, Point3D(5, 0, 0));

// Set velocity directly (useful for character controllers)
GorillaPhysicsSystem1.RemoteBodyVelocity(CharacterCtrl, Point3D(0, 0, 3));

// Set angular velocity
GorillaPhysicsSystem1.RemoteBodyAngularVelocity(WheelMesh, Point3D(5, 0, 0));

// Apply angular impulse at a point
GorillaPhysicsSystem1.RemoteBodyAngularImpulse(CrateModel,
  Point3D(0, 10, 0), Point3D(1, 0, 0));

// Teleport a body (override physics position)
GorillaPhysicsSystem1.RemoteBodyTransform(CrateModel,
  Point3D(0, -5, 0), Point3D(0, 0, 0));

Collision Events

Global Events

GorillaPhysicsSystem1.OnBeginContact := procedure(ASender: TObject;
  const ABody1, ABody2: TGorillaPhysicsBody)
begin
  // Two bodies started colliding
end;

GorillaPhysicsSystem1.OnEndContact := procedure(ASender: TObject;
  const ABody1, ABody2: TGorillaPhysicsBody)
begin
  // Two bodies stopped colliding
end;

Per-Collider Events

Settings.OnBeginContact := procedure(ASender: TObject;
  const AOffset, ANormal: TPoint3D; ABody1, ABody2: TGorillaPhysicsBody)
begin
  // This specific collider started a contact
end;

Settings.OnEndContact := procedure(ASender: TObject;
  const AOffset, ANormal: TPoint3D; ABody1, ABody2: TGorillaPhysicsBody)
begin
  // This specific collider ended a contact
end;

Step Events

GorillaPhysicsSystem1.OnBeginStep := HandleBeginStep;  // before simulation
GorillaPhysicsSystem1.OnEndStep := HandleEndStep;        // after simulation
GorillaPhysicsSystem1.OnBeginUpdate := HandleBeginUpdate; // before body sync
GorillaPhysicsSystem1.OnEndUpdate := HandleEndUpdate;     // after body sync

Design-Time Collider Prefabs

Use the Colliders collection property to define colliders at design-time. Each TGorillaPhysicsColliderPrefab links a TControl3D to a collider type and settings. They are automatically registered when the physics system activates.

The Joints collection works similarly for design-time joint configuration.

Async Physics

Enable threaded physics computation for better performance:

GorillaPhysicsSystem1.Async := True;

// When accessing bodies from the main thread, block first:
GorillaPhysicsSystem1.Block();
try
  GorillaPhysicsSystem1.RemoteBodyImpulse(SomeBody, Point3D(0, -5, 0));
finally
  GorillaPhysicsSystem1.Unblock();
end;

Physics Character Controller

TGorillaPhysicsCharacterController (in Gorilla.PhysicsCharacterController) provides a physics-driven character that works with the physics system for ground detection, slopes, and collision response.

Performance Tips

  • Use static bodies for all non-moving geometry (floors, walls, terrain)
  • Enable AllowSleep to let idle bodies rest
  • Set Accuracy between 5-15 (higher = more accurate but slower)
  • Use simple collider shapes (box, sphere, capsule) instead of mesh colliders
  • Use collision layers to reduce unnecessary collision checks
  • Enable Async mode for complex scenes
  • Call Step() at a fixed interval (33ms recommended) for stable simulation

Best Practices

  • Always call Step() from a timer, not from the render loop
  • Use Block()/Unblock() when accessing bodies in async mode
  • Prefer capsule colliders for characters (better slope handling)
  • Use kinematic bodies for player-controlled objects that should push other objects
  • Set appropriate friction and restitution values for realistic behavior
  • Use sensors (Data.Sensor := True) for trigger volumes that detect overlap without physical response
  • Debug with RenderColliders := True to visualize all collider shapes