Skip to content

Spielphysik für Web-Spiele

Physiksimulation erweckt Spiele zum Leben: fallende Objekte, springende Bälle, Ragdolls, Fahrzeuge und zerstörbare Umgebungen. Dieser Leitfaden behandelt die wichtigsten Physik-Bibliotheken für Web-Spiele, mit echten Codebeispielen und ehrlichen Vor- und Nachteilen.

Auf einen Blick

EngineDimensionLeistungGrößeSchwierigkeitSoft BodiesFahrzeugeCCDDeterminismus
Rapier2D/3D⭐⭐⭐⭐⭐1,4 MBmittel
Cannon-es3D⭐⭐⭐150 KBleicht
Ammo.js3D⭐⭐⭐⭐⭐1-2 MBschwer⚠️
Jolt3D⭐⭐⭐⭐⭐schwer
Oimo.js3D⭐⭐⭐100 KBleicht
Matter.js2D⭐⭐⭐80 KBleicht⚠️
Planck.js2D⭐⭐⭐⭐120 KBmittel⚠️
p2-es2D⭐⭐⭐100 KBmittel
Box2D WASM2D⭐⭐⭐⭐⭐300 KBschwer

Legende:

  • CCD = Continuous Collision Detection, verhindert, dass schnelle Objekte durch Wände tunneln
  • ⚠️ Determinismus = mit festem Zeitschritt möglich, aber plattformübergreifend nicht garantiert

Kurze Empfehlungen

Deine LageBeste Wahl
3D-Spiel in ProduktionRapier — beste Leistung, moderne API, aktive Entwicklung
Lernen und PrototypCannon-es (3D) oder Matter.js (2D) — einfache APIs, leichtes Debugging
FahrzeugphysikRapier oder Ammo.js — beide haben Raycast-Fahrzeugcontroller
Soft Bodies, Stoff, SeileAmmo.js oder Jolt (JoltPhysics.js) — beide unterstützen Stoff und Soft Bodies, Jolts WASM-Port wird aktiver gepflegt
Präziser 2D-PlattformerPlanck.js — Box2D-Algorithmen, deterministisch mit festem Zeitschritt
Maximale 2D-LeistungBox2D WASM — native Geschwindigkeit im Browser
Kleinste Bundle-GrößeOimo.js (3D) oder Matter.js (2D)

Ausführlicher Vergleich

3D-Physik-Engines

EngineSpracheGrößeLeistungAm besten für
RapierRust/WASM~1,4 MBausgezeichnetSpiele in Produktion, komplexe Simulationen
Cannon-esJavaScript~150 KBgutPrototypen, einfache Spiele
Ammo.jsC++/WASM~1-2 MBausgezeichnetAAA-Funktionen, Soft Bodies, Fahrzeuge
JoltC++/WASMWASMausgezeichnetAAA-Funktionen mit aktiver Pflege
Oimo.jsJavaScript~100 KBguteinfache Spiele, schnelle Prototypen

2D-Physik-Engines

EngineSpracheGrößeLeistungAm besten für
Matter.jsJavaScript~80 KBgutvisuelle Spiele, Prototypen
Planck.jsJavaScript~120 KBgutPlattformer, präzise Physik
p2-esJavaScript~100 KBgutConstraints, Mechanismen
Box2D WASMC++/WASM~300 KBausgezeichnetviele Körper

3D-Physik-Engines

Rapier — die moderne Wahl

Rapier ist eine Physik-Engine in Rust mit JavaScript- und WASM-Bindings. Sie ist 2025 und 2026 die leistungsstärkste Option für Web-Spiele, mit 2- bis 5-facher Beschleunigung gegenüber der Version von 2024.

Installation:

bash
npm install @dimforge/rapier3d
# Or with SIMD (faster, requires modern browsers):
npm install @dimforge/rapier3d-simd

Grundaufbau:

js
import RAPIER from '@dimforge/rapier3d'

// Initialize (async required for WASM)
await RAPIER.init()

// Create world with gravity
const gravity = { x: 0, y: -9.81, z: 0 }
const world = new RAPIER.World(gravity)

// Create ground (static body)
const groundDesc = RAPIER.RigidBodyDesc.fixed()
const groundBody = world.createRigidBody(groundDesc)
const groundCollider = RAPIER.ColliderDesc.cuboid(50, 0.1, 50)
world.createCollider(groundCollider, groundBody)

// Create falling box (dynamic body)
const boxDesc = RAPIER.RigidBodyDesc.dynamic()
  .setTranslation(0, 10, 0)
const boxBody = world.createRigidBody(boxDesc)
const boxCollider = RAPIER.ColliderDesc.cuboid(0.5, 0.5, 0.5)
  .setDensity(1.0)
  .setRestitution(0.5)
world.createCollider(boxCollider, boxBody)

Einbindung in die Spielschleife:

js
const FIXED_TIMESTEP = 1 / 60

function physicsStep() {
  world.step()
}

function gameLoop() {
  physicsStep()
  
  // Sync render objects with physics
  const position = boxBody.translation()
  const rotation = boxBody.rotation()
  
  // Update your Three.js/Babylon mesh
  mesh.position.set(position.x, position.y, position.z)
  mesh.quaternion.set(rotation.x, rotation.y, rotation.z, rotation.w)
  
  requestAnimationFrame(gameLoop)
}

Kollisionserkennung:

js
// Event-based collision detection
world.contactPairsWith(boxCollider, (otherCollider) => {
  console.log('Box is touching:', otherCollider)
})

// Ray casting
const ray = new RAPIER.Ray({ x: 0, y: 10, z: 0 }, { x: 0, y: -1, z: 0 })
const hit = world.castRay(ray, 100, true)
if (hit) {
  const hitPoint = ray.pointAt(hit.timeOfImpact)
  console.log('Hit at:', hitPoint)
}

Gelenke:

js
// Create a hinge joint (door)
const jointData = RAPIER.JointData.revolute(
  { x: 0, y: 0, z: 0 },  // Anchor on body1
  { x: -1, y: 0, z: 0 }, // Anchor on body2
  { x: 0, y: 1, z: 0 }   // Rotation axis
)
world.createImpulseJoint(jointData, body1, body2, true)

Fahrzeugcontroller:

js
// Create chassis rigid body
const chassisDesc = RAPIER.RigidBodyDesc.dynamic()
  .setTranslation(0, 2, 0)
const chassis = world.createRigidBody(chassisDesc)
const chassisCollider = RAPIER.ColliderDesc.cuboid(1, 0.5, 2)
  .setDensity(100)
world.createCollider(chassisCollider, chassis)

// Create vehicle controller
const vehicle = world.createVehicleController(chassis)

// Add wheels (front-left, front-right, rear-left, rear-right)
const suspensionRestLength = 0.3
const wheelRadius = 0.4

// Front wheels (steering)
vehicle.addWheel(
  { x: -0.8, y: 0, z: 1.2 },   // Connection point
  { x: 0, y: -1, z: 0 },       // Suspension direction
  { x: -1, y: 0, z: 0 },       // Axle direction
  suspensionRestLength,
  wheelRadius
)
vehicle.addWheel(
  { x: 0.8, y: 0, z: 1.2 },
  { x: 0, y: -1, z: 0 },
  { x: -1, y: 0, z: 0 },
  suspensionRestLength,
  wheelRadius
)

// Rear wheels (drive)
vehicle.addWheel(
  { x: -0.8, y: 0, z: -1.2 },
  { x: 0, y: -1, z: 0 },
  { x: -1, y: 0, z: 0 },
  suspensionRestLength,
  wheelRadius
)
vehicle.addWheel(
  { x: 0.8, y: 0, z: -1.2 },
  { x: 0, y: -1, z: 0 },
  { x: -1, y: 0, z: 0 },
  suspensionRestLength,
  wheelRadius
)

// Configure suspension for all wheels
for (let i = 0; i < 4; i++) {
  vehicle.setWheelSuspensionStiffness(i, 30)
  vehicle.setWheelSuspensionCompression(i, 4.4)
  vehicle.setWheelSuspensionRelaxation(i, 2.3)
  vehicle.setWheelMaxSuspensionTravel(i, 0.5)
  vehicle.setWheelFrictionSlip(i, 2)
}

// In game loop
function updateVehicle(steering, engineForce, brakeForce) {
  // Steering (front wheels only)
  vehicle.setWheelSteering(0, steering)
  vehicle.setWheelSteering(1, steering)
  
  // Engine (rear wheels)
  vehicle.setWheelEngineForce(2, engineForce)
  vehicle.setWheelEngineForce(3, engineForce)
  
  // Brakes (all wheels)
  for (let i = 0; i < 4; i++) {
    vehicle.setWheelBrake(i, brakeForce)
  }
  
  // Update vehicle physics
  vehicle.updateVehicle(world.timestep)
}

Vorteile:

  • Beste Leistung (WASM plus SIMD)
  • Sehr genaue Kollisionserkennung
  • Plattformübergreifender Determinismus (gleiche Eingaben ergeben gleiche Ausgaben)
  • Aktive Entwicklung, moderne API
  • Continuous Collision Detection, kein Tunneln
  • Charakter- und Fahrzeugcontroller eingebaut

Nachteile:

  • Größeres Bundle (~1,4 MB)
  • Asynchrone Initialisierung nötig
  • Komplexere API als reine JS-Alternativen
  • WASM-Debugging kann heikel sein

Cannon-es — einfach und wirkungsvoll

Cannon-es ist der gepflegte Fork von Cannon.js. Reines JavaScript, leicht verständlich, gut zum Lernen und für Prototypen.

Installation:

bash
npm install cannon-es

Grundaufbau:

js
import * as CANNON from 'cannon-es'

// Create world
const world = new CANNON.World({
  gravity: new CANNON.Vec3(0, -9.81, 0)
})

// Ground
const groundBody = new CANNON.Body({
  type: CANNON.Body.STATIC,
  shape: new CANNON.Plane()
})
groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0)
world.addBody(groundBody)

// Falling sphere
const sphereBody = new CANNON.Body({
  mass: 1,
  shape: new CANNON.Sphere(0.5),
  position: new CANNON.Vec3(0, 10, 0)
})
sphereBody.linearDamping = 0.1
world.addBody(sphereBody)

Spielschleife:

js
const TIMESTEP = 1 / 60

function animate() {
  world.step(TIMESTEP)
  
  // Sync with Three.js
  mesh.position.copy(sphereBody.position)
  mesh.quaternion.copy(sphereBody.quaternion)
  
  requestAnimationFrame(animate)
}

Kollisions-Events:

js
sphereBody.addEventListener('collide', (event) => {
  const contact = event.contact
  const impactVelocity = contact.getImpactVelocityAlongNormal()
  
  if (Math.abs(impactVelocity) > 5) {
    console.log('Hard impact!')
  }
})

Constraints:

js
// Distance constraint (rope-like)
const constraint = new CANNON.DistanceConstraint(
  bodyA, bodyB, 
  2 // distance
)
world.addConstraint(constraint)

// Hinge constraint
const hinge = new CANNON.HingeConstraint(bodyA, bodyB, {
  pivotA: new CANNON.Vec3(1, 0, 0),
  axisA: new CANNON.Vec3(0, 1, 0),
  pivotB: new CANNON.Vec3(-1, 0, 0),
  axisB: new CANNON.Vec3(0, 1, 0)
})
world.addConstraint(hinge)

Vorteile:

  • Reines JavaScript, keine WASM-Komplexität
  • Kleines Bundle (~150 KB)
  • Leicht zu lernen und zu debuggen
  • Läuft überall
  • Gute Three.js-Integration
  • Gute Dokumentation

Nachteile:

  • Langsamer als WASM-Alternativen
  • Schwächelt bei vielen Körpern (über 100)
  • Eingeschränkte Trimesh-Unterstützung
  • Kein eingebautes CCD, Tunneln möglich
  • Weniger aktive Entwicklung

Ammo.js — die volle Kraft von Bullet Physics

Ammo.js ist die Bullet-Physics-Engine, kompiliert nach WebAssembly. Maximaler Funktionsumfang, inklusive Soft Bodies, Fahrzeugen und fortgeschrittenen Constraints.

Installation:

bash
npm install ammo.js
# Or use from CDN

Grundaufbau:

js
import Ammo from 'ammo.js'

let physicsWorld

async function initPhysics() {
  await Ammo()
  
  const collisionConfig = new Ammo.btDefaultCollisionConfiguration()
  const dispatcher = new Ammo.btCollisionDispatcher(collisionConfig)
  const broadphase = new Ammo.btDbvtBroadphase()
  const solver = new Ammo.btSequentialImpulseConstraintSolver()
  
  physicsWorld = new Ammo.btDiscreteDynamicsWorld(
    dispatcher, broadphase, solver, collisionConfig
  )
  physicsWorld.setGravity(new Ammo.btVector3(0, -9.81, 0))
}

function createBox(mass, width, height, depth, x, y, z) {
  const transform = new Ammo.btTransform()
  transform.setIdentity()
  transform.setOrigin(new Ammo.btVector3(x, y, z))
  
  const motionState = new Ammo.btDefaultMotionState(transform)
  const shape = new Ammo.btBoxShape(
    new Ammo.btVector3(width / 2, height / 2, depth / 2)
  )
  
  const localInertia = new Ammo.btVector3(0, 0, 0)
  if (mass > 0) {
    shape.calculateLocalInertia(mass, localInertia)
  }
  
  const rbInfo = new Ammo.btRigidBodyConstructionInfo(
    mass, motionState, shape, localInertia
  )
  const body = new Ammo.btRigidBody(rbInfo)
  
  physicsWorld.addRigidBody(body)
  return body
}

Soft Bodies (Stoff):

js
function createCloth(width, height, segments) {
  const softBodyHelpers = new Ammo.btSoftBodyHelpers()
  
  const corner00 = new Ammo.btVector3(-width/2, height, 0)
  const corner10 = new Ammo.btVector3(width/2, height, 0)
  const corner01 = new Ammo.btVector3(-width/2, 0, 0)
  const corner11 = new Ammo.btVector3(width/2, 0, 0)
  
  const softBody = softBodyHelpers.CreatePatch(
    physicsWorld.getWorldInfo(),
    corner00, corner10, corner01, corner11,
    segments, segments,
    0, true
  )
  
  const sbConfig = softBody.get_m_cfg()
  sbConfig.set_viterations(10)
  sbConfig.set_piterations(10)
  
  softBody.setTotalMass(0.9, false)
  Ammo.castObject(softBody, Ammo.btCollisionObject)
    .getCollisionShape().setMargin(0.05)
  
  physicsWorld.addSoftBody(softBody, 1, -1)
  return softBody
}

Fahrzeugphysik:

js
function createVehicle(chassisBody) {
  const tuning = new Ammo.btVehicleTuning()
  const rayCaster = new Ammo.btDefaultVehicleRaycaster(physicsWorld)
  const vehicle = new Ammo.btRaycastVehicle(tuning, chassisBody, rayCaster)
  
  vehicle.setCoordinateSystem(0, 1, 2)
  physicsWorld.addAction(vehicle)
  
  // Add wheels
  const wheelRadius = 0.4
  const wheelWidth = 0.3
  const suspensionRestLength = 0.3
  
  const wheelDirectionCS = new Ammo.btVector3(0, -1, 0)
  const wheelAxleCS = new Ammo.btVector3(-1, 0, 0)
  
  function addWheel(isFront, pos) {
    const wheelInfo = vehicle.addWheel(
      pos, wheelDirectionCS, wheelAxleCS,
      suspensionRestLength, wheelRadius, tuning, isFront
    )
    wheelInfo.set_m_suspensionStiffness(20)
    wheelInfo.set_m_wheelsDampingRelaxation(2.3)
    wheelInfo.set_m_wheelsDampingCompression(4.4)
    wheelInfo.set_m_frictionSlip(1000)
    wheelInfo.set_m_rollInfluence(0.1)
  }
  
  addWheel(true, new Ammo.btVector3(1, 0, 1.5))   // Front left
  addWheel(true, new Ammo.btVector3(-1, 0, 1.5))  // Front right
  addWheel(false, new Ammo.btVector3(1, 0, -1.5)) // Rear left
  addWheel(false, new Ammo.btVector3(-1, 0, -1.5))// Rear right
  
  return vehicle
}

Vorteile:

  • Der vollständigste Funktionsumfang
  • Soft Bodies, Stoff, Seile
  • Fortgeschrittene Fahrzeugphysik
  • Praxiserprobt, in vielen AAA-Spielen im Einsatz
  • Sehr konfigurierbar

Nachteile:

  • Komplexe, geschwätzige API
  • Großes Bundle
  • Speicherverwaltung nötig, Objekte müssen zerstört werden
  • Steile Lernkurve
  • Verstreute Dokumentation
  • Nicht plattformübergreifend deterministisch, nur auf demselben Gerät und mit sorgfältiger Konfiguration

Jolt — moderne 3D-Physik auf AAA-Niveau

Jolt Physics ist die Engine hinter Spielen wie Horizon Forbidden West, und JoltPhysics.js bringt sie als WASM-Port in den Browser. Sie ist ein starker Mittelweg zwischen Rapier und Ammo.js: mehr Funktionen als Rapier (Soft Bodies, Stoff, ein Fahrzeugcontroller mit Rädern) bei aktiver Pflege, die Ammo.js fehlt. Das npm-Paket heißt jolt-physics, und es gibt fertige Integrationen für React Three Fiber (@react-three/jolt) und Babylon.js.

bash
npm install jolt-physics

Wie Rapier ist es asynchron initialisiertes WASM mit einer geschwätzigen, aber vollständigen API, die die C++-Schnittstelle spiegelt. Greif zu Jolt, wenn du Funktionen der Bullet-Klasse willst (Soft Bodies, Fahrzeuge), aber eine gepflegte, moderne Codebasis statt Ammo.js bevorzugst.


Oimo.js — leichtgewichtig und schnell

Oimo.js ist eine leichtgewichtige 3D-Physik-Engine. Gut für einfache Spiele, in denen du keine fortgeschrittenen Funktionen brauchst.

Installation:

bash
npm install oimo

Grundaufbau:

js
import * as OIMO from 'oimo'

const world = new OIMO.World({
  timestep: 1/60,
  iterations: 8,
  broadphase: 2, // 1: brute, 2: sweep & prune, 3: volume tree
  worldscale: 1,
  random: true,
  gravity: [0, -9.8, 0]
})

// Create ground
world.add({
  type: 'box',
  size: [100, 1, 100],
  pos: [0, -0.5, 0],
  move: false
})

// Create falling sphere
const sphere = world.add({
  type: 'sphere',
  size: [1],
  pos: [0, 10, 0],
  move: true,
  density: 1,
  friction: 0.4,
  restitution: 0.2
})

Spielschleife:

js
function animate() {
  world.step()
  
  // Get position/rotation
  const pos = sphere.getPosition()
  const rot = sphere.getQuaternion()
  
  mesh.position.set(pos.x, pos.y, pos.z)
  mesh.quaternion.set(rot.x, rot.y, rot.z, rot.w)
  
  requestAnimationFrame(animate)
}

Vorteile:

  • Sehr klein (~100 KB)
  • Einfache API
  • Gute Leistung bei einfachen Szenen
  • Eingebaute Babylon.js-Unterstützung

Nachteile:

  • Wenige Formen, nur Primitive
  • Keine Soft Bodies
  • Dünne Dokumentation
  • Weniger aktive Entwicklung
  • Wenige Gelenkoptionen

2D-Physik-Engines

Matter.js — schön und eingängig

Matter.js ist eine funktionsreiche 2D-Physik-Engine mit hervorragendem Rendering und guten Debug-Werkzeugen.

Installation:

bash
npm install matter-js

Grundaufbau:

js
import Matter from 'matter-js'

const { Engine, Render, World, Bodies, Runner } = Matter

// Create engine
const engine = Engine.create()

// Create renderer (optional, great for debugging)
const render = Render.create({
  element: document.body,
  engine: engine,
  options: {
    width: 800,
    height: 600,
    wireframes: false
  }
})

// Create bodies
const ground = Bodies.rectangle(400, 580, 810, 60, { 
  isStatic: true 
})

const box = Bodies.rectangle(400, 200, 80, 80, {
  restitution: 0.8,
  friction: 0.5
})

const circle = Bodies.circle(300, 100, 40, {
  restitution: 0.9
})

// Add to world
World.add(engine.world, [ground, box, circle])

// Run
Render.run(render)
Runner.run(Runner.create(), engine)

Kollisions-Events:

js
Matter.Events.on(engine, 'collisionStart', (event) => {
  event.pairs.forEach(pair => {
    console.log('Collision between:', pair.bodyA.label, pair.bodyB.label)
  })
})

Constraints:

js
// Pin constraint
const pin = Matter.Constraint.create({
  pointA: { x: 400, y: 100 },
  bodyB: box,
  stiffness: 0.9
})

// Spring between bodies
const spring = Matter.Constraint.create({
  bodyA: box,
  bodyB: circle,
  stiffness: 0.01,
  length: 100
})

World.add(engine.world, [pin, spring])

Mausinteraktion:

js
const mouse = Matter.Mouse.create(render.canvas)
const mouseConstraint = Matter.MouseConstraint.create(engine, {
  mouse: mouse,
  constraint: {
    stiffness: 0.2,
    render: { visible: false }
  }
})
World.add(engine.world, mouseConstraint)

Vorteile:

  • Schönes Standard-Rendering
  • Gut zum Lernen und Prototypen
  • Eingängige API
  • Gute Dokumentation
  • Aktive Community
  • Standardmäßig deterministisch, Matter.Runner nutzt jetzt einen festen deterministischen Zeitschritt (der nicht feste Zeitschritt wurde in v0.20.0 entfernt)

Nachteile:

  • Kein CCD, schnelle Objekte können tunneln, mit Substepping abmildern
  • Leistungsprobleme bei vielen Körpern
  • Keine WASM-Option
  • Begrenzte Präzision bei komplexen Simulationen

Planck.js — Box2D für JavaScript

Planck.js ist eine vollständige Neufassung von Box2D in JavaScript. Praxiserprobte Physik, deterministisch bei festem Zeitschritt.

Installation:

bash
npm install planck

Grundaufbau:

js
import { World, Vec2, Box, Circle, Edge } from 'planck'

// Create world
const world = new World({
  gravity: Vec2(0, -10)
})

// Create ground
const ground = world.createBody()
ground.createFixture({
  shape: Edge(Vec2(-40, 0), Vec2(40, 0))
})

// Create dynamic box
const box = world.createBody({
  type: 'dynamic',
  position: Vec2(0, 10)
})
box.createFixture({
  shape: Box(1, 1),
  density: 1,
  friction: 0.3,
  restitution: 0.5
})

Spielschleife mit festem Zeitschritt:

js
const TIMESTEP = 1 / 60
const VELOCITY_ITERATIONS = 8
const POSITION_ITERATIONS = 3

function gameLoop() {
  world.step(TIMESTEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS)
  
  // Iterate all bodies
  for (let body = world.getBodyList(); body; body = body.getNext()) {
    const pos = body.getPosition()
    const angle = body.getAngle()
    // Update your sprites...
  }
  
  requestAnimationFrame(gameLoop)
}

Kollisions-Callbacks:

js
world.on('begin-contact', (contact) => {
  const fixtureA = contact.getFixtureA()
  const fixtureB = contact.getFixtureB()
  console.log('Contact started')
})

world.on('end-contact', (contact) => {
  console.log('Contact ended')
})

world.on('pre-solve', (contact, oldManifold) => {
  // Can disable contact here
  // contact.setEnabled(false)
})

Gelenke:

js
import { RevoluteJoint, DistanceJoint, PrismaticJoint } from 'planck'

// Revolute joint (hinge)
const joint = world.createJoint(RevoluteJoint({
  bodyA: ground,
  bodyB: box,
  localAnchorA: Vec2(0, 5),
  localAnchorB: Vec2(-1, 0),
  enableMotor: true,
  maxMotorTorque: 1000,
  motorSpeed: 2
}))

// Distance joint (spring)
world.createJoint(DistanceJoint({
  bodyA: boxA,
  bodyB: boxB,
  localAnchorA: Vec2(0, 0),
  localAnchorB: Vec2(0, 0),
  length: 5,
  stiffness: 10,
  damping: 0.5
}))

Vorteile:

  • Deterministisch mit festem Zeitschritt
  • Gut dokumentiert, die Box2D-Doku gilt
  • Gute Leistung
  • TypeScript-Unterstützung
  • Kleines Bundle

Nachteile:

  • CCD erfasst keine Gelenke, schnelle über Gelenke verbundene Objekte können sich dehnen
  • Steilere Lernkurve als Matter.js
  • Kein eingebauter Renderer
  • Box2D-Eigenheiten, der Maßstab der Einheiten zählt

p2-es — flexible 2D-Physik

p2-es ist der gepflegte Fork von p2.js. Gut für Spiele, die komplexe Constraints und Mechanismen brauchen.

Installation:

bash
npm install p2-es

Grundaufbau:

js
import * as p2 from 'p2-es'

const world = new p2.World({
  gravity: [0, -9.81]
})

// Ground
const groundBody = new p2.Body({
  mass: 0, // static
  position: [0, -1]
})
groundBody.addShape(new p2.Plane())
world.addBody(groundBody)

// Dynamic circle
const circleBody = new p2.Body({
  mass: 1,
  position: [0, 5]
})
circleBody.addShape(new p2.Circle({ radius: 0.5 }))
world.addBody(circleBody)

Fortgeschrittene Constraints:

js
// Gear constraint
const gear = new p2.GearConstraint(bodyA, bodyB, {
  ratio: 2 // bodyB rotates twice as fast
})
world.addConstraint(gear)

// Prismatic constraint (slider)
const prismatic = new p2.PrismaticConstraint(bodyA, bodyB, {
  localAnchorA: [0, 0],
  localAnchorB: [0, 0],
  localAxisA: [1, 0],
  disableRotationalLock: false
})
world.addConstraint(prismatic)

// Lock constraint (weld)
const lock = new p2.LockConstraint(bodyA, bodyB)
world.addConstraint(lock)

Kontaktmaterialien:

js
const ice = new p2.Material()
const rubber = new p2.Material()

const iceRubber = new p2.ContactMaterial(ice, rubber, {
  friction: 0.1,
  restitution: 0.9
})
world.addContactMaterial(iceRubber)

// Apply to shapes
iceBody.shapes[0].material = ice
rubberBody.shapes[0].material = rubber

Vorteile:

  • Reichhaltiges Constraint-System
  • Kontaktmaterialien
  • Gut für Mechanismen und Maschinen
  • Schlafende Körper, gut für die Leistung
  • ES-Module, tree-shakable

Nachteile:

  • Kein eingebauter Renderer
  • Einige Formenpaare nicht unterstützt
  • Weniger aktiv als die Alternativen
  • Lücken in der Dokumentation

Tipps zur Leistung

1. Nutz einen festen Zeitschritt

js
const TIMESTEP = 1 / 60
let accumulator = 0

function gameLoop(deltaTime) {
  accumulator += deltaTime
  
  while (accumulator >= TIMESTEP) {
    world.step(TIMESTEP)
    accumulator -= TIMESTEP
  }
  
  // Interpolate for smooth rendering
  const alpha = accumulator / TIMESTEP
  // lerp(previousState, currentState, alpha)
}

2. Lass inaktive Körper schlafen

Die meisten Engines unterstützen Schlafen. Schalte es ein:

js
// Cannon-es
world.allowSleep = true
body.allowSleep = true
body.sleepSpeedLimit = 0.1
body.sleepTimeLimit = 1

// Rapier
bodyDesc.setCanSleep(true)

3. Nutz einfache Kollisionsformen

js
// GOOD: Simple primitives
const sphere = new CANNON.Sphere(1)
const box = new CANNON.Box(new CANNON.Vec3(1, 1, 1))

// AVOID: Complex trimesh for dynamic bodies
const trimesh = new CANNON.Trimesh(vertices, indices) // Slow!

4. Reduziere Solver-Iterationen, vorsichtig

js
// Cannon-es
world.solver.iterations = 5 // Default 10

// Rapier - configured at world creation

5. Lass Physik in einem Web Worker laufen

js
// main.js
const worker = new Worker('physics-worker.js')

worker.postMessage({ type: 'step', deltaTime: 1/60 })
worker.onmessage = (e) => {
  const { positions, rotations } = e.data
  // Update render objects
}

// physics-worker.js
importScripts('cannon-es.js')
const world = new CANNON.World()

onmessage = (e) => {
  if (e.data.type === 'step') {
    world.step(e.data.deltaTime)
    postMessage({
      positions: bodies.map(b => b.position.toArray()),
      rotations: bodies.map(b => b.quaternion.toArray())
    })
  }
}

Wann was passt

SzenarioEmpfehlungWarum
3D-Spiel in ProduktionRapierBeste Leistung, moderne API, Fahrzeuge
3D-PrototypCannon-esEinfach, gut zu debuggen
Soft Bodies, Stoff, SeileAmmo.js oder JoltBeide unterstützen Stoff und Soft Bodies, Jolts WASM-Port (JoltPhysics.js) wird aktiver gepflegt
Einfaches 3D-Browser-SpielOimo.jsWinzig, ausreichend
2D-Game-JamMatter.jsSchnell eingerichtet, Rendering eingebaut
Präziser PlattformerPlanck.jsDeterminismus mit festem Zeitschritt, gut dokumentiert
Komplexe 2D-Mechanismenp2-esReichhaltiges Constraint-System
Leistungskritisches 2DBox2D WASMSchnellste 2D-Option, echtes CCD

Integration mit Renderern

Three.js + Rapier

js
import * as THREE from 'three'
import RAPIER from '@dimforge/rapier3d'

await RAPIER.init()

const scene = new THREE.Scene()
const world = new RAPIER.World({ x: 0, y: -9.81, z: 0 })

const bodies = new Map() // physics body -> mesh

function createPhysicsBox(x, y, z) {
  // Physics
  const bodyDesc = RAPIER.RigidBodyDesc.dynamic().setTranslation(x, y, z)
  const body = world.createRigidBody(bodyDesc)
  const collider = RAPIER.ColliderDesc.cuboid(0.5, 0.5, 0.5)
  world.createCollider(collider, body)
  
  // Render
  const mesh = new THREE.Mesh(
    new THREE.BoxGeometry(1, 1, 1),
    new THREE.MeshStandardMaterial({ color: 0x00ff00 })
  )
  scene.add(mesh)
  
  bodies.set(body, mesh)
  return body
}

function syncPhysics() {
  bodies.forEach((mesh, body) => {
    const pos = body.translation()
    const rot = body.rotation()
    mesh.position.set(pos.x, pos.y, pos.z)
    mesh.quaternion.set(rot.x, rot.y, rot.z, rot.w)
  })
}

PixiJS + Matter.js

js
import * as PIXI from 'pixi.js'
import Matter from 'matter-js'

const app = new PIXI.Application({ width: 800, height: 600 })
document.body.appendChild(app.view)

const engine = Matter.Engine.create()
const bodies = new Map()

function createPhysicsSprite(texture, x, y, width, height) {
  // Physics
  const body = Matter.Bodies.rectangle(x, y, width, height)
  Matter.World.add(engine.world, body)
  
  // Render
  const sprite = new PIXI.Sprite(texture)
  sprite.anchor.set(0.5)
  app.stage.addChild(sprite)
  
  bodies.set(body, sprite)
  return body
}

app.ticker.add(() => {
  Matter.Engine.update(engine, 1000 / 60)
  
  bodies.forEach((sprite, body) => {
    sprite.position.set(body.position.x, body.position.y)
    sprite.rotation = body.angle
  })
})

Typische Stolperfallen

Der Maßstab zählt

Physik-Engines arbeiten am besten mit realem Maßstab (1 Einheit = 1 Meter). Nutz nicht direkt Pixelkoordinaten.

js
// BAD: Using pixel positions
const body = Bodies.circle(400, 300, 50) // 50 pixel radius?

// GOOD: Use a scale factor
const SCALE = 50 // 50 pixels per meter
const body = Bodies.circle(8, 6, 1) // 1 meter radius
// Then multiply by SCALE when rendering

Speicherlecks bei WASM-Engines

Räum Körper beim Entfernen immer sauber auf:

js
// Rapier
world.removeRigidBody(body)

// Ammo.js
physicsWorld.removeRigidBody(body)
Ammo.destroy(body)
Ammo.destroy(shape)
Ammo.destroy(motionState)

Tunneln, wenn Objekte einander durchdringen

Schnelle Objekte können durch dünne Wände tunneln. Lösungen:

js
// Rapier: Enable CCD
const bodyDesc = RAPIER.RigidBodyDesc.dynamic().setCcdEnabled(true)

// Cannon-es: Use smaller timesteps or thicker walls
world.step(1/120) // 120 Hz instead of 60

Verwandt

Externe Ressourcen