Physics
Kaigen's physics is a port of Box3D written into the engine: no external library, the same on every platform, and stepped on every lane. Like everything else, it's components on entities.
| To make... | Add |
|---|---|
| A wall, the floor | ColliderBody + StaticBody |
| Something that falls and bounces | ColliderBody + WorldTransform, then ecs_rigidbody_body_add |
| A moving platform you animate | ColliderBody + WorldTransform + KinematicBody |
| A trigger zone | ColliderBody + PhysicsSensor |
Colliders are spheres, capsules, boxes, convex hulls, compounds of those, triangle meshes and terrain: collider_sphere, collider_capsule, collider_box, and so on.
EcsEntity crate = ecs_entity_create(world);
ecs_component_set(world, crate, WorldTransform,
{.position = {0, 5, 0}, .rotation = quat_identity(), .scale = V3_ONE});
ecs_component_set(world, crate, ColliderBody,
{.collider = collider_box(V3_ZERO, (v3){0.5f, 0.5f, 0.5f}),
.rot = quat_identity(), .scale = 1.0f});
ecs_rigidbody_body_add(world, crate, (RigidBody){.inverse_mass = 1.0f / 20.0f, // 20 kg
.friction = 0.6f});Stepping
Physics runs at a fixed rate, so it behaves the same at 30 or 144 frames per second. The starting template has the loop already: fixed_timestep_begin says how many steps this frame needs, and each one is a flush of your fixed-step systems followed by ecs_rigidbody_step. Put anything that moves bodies in that loop.
Asking questions
Raycasts, shape casts and overlaps work on the EcsPhysicsWorld resource, from any system after the step:
EcsPhysicsHit hit;
v3 end = v3_add(eye, v3_scale(forward, 50.0f));
if (ecs_physics_raycast(pw, eye, end, &(EcsPhysicsQuery){.ignore = me}, &hit)) {
// hit.entity, hit.hit.point, hit.hit.normal
}Trigger zones report who came in and out in PhysicsSensorContacts.entered and .exited.
Filtering uses a category, a mask and a group on each body (PhysicsFilter), the same rules as Box2D.
Also in the box
- Joints, motors, wheels and anti-roll bars for vehicles.
- Ragdolls and active ragdolls, cloth, and IK.
- Navigation meshes and pathfinding.
- A spatial grid for neighbour queries over thousands of moving things (crowds, swarms) without colliders.
Worth knowing
- Never set the
WorldTransformof a dynamic body to move it. Push it withecs_rigidbody_add_impulseorecs_rigidbody_add_force, or make it kinematic. - A scene stores the authored
EcsCollider; the runtimeColliderBodyis built from it when the scene loads. ecs_rigidbody_shutdownbefore destroying the world frees the physics world.
The ECS side is hz/src/engine/ecs/ecs_physics/ and ecs_rigidbody/, and the shapes and queries are hz/src/engine/physics/physics.h.