logo

Babylon.js Market

By Lawrence

5 minutes

Right now your capsule walks straight through walls, and there is nothing to kick. The mover snaps the mesh to whatever spot the math picks. The walls are only painted boxes.

One component fixes both problems. It is called Physics. But it also changes how Movement works. That second change is what this lesson is about.

Add physics bodies and a ball

Give the ground and the four walls a static body. A static body never moves and has infinite mass. Give the player a dynamic capsule, which falls and collides. Then add the ball as a dynamic sphere:

src/scenes/soccer.json
"Pitch":  { "components": { "Physics": { "shapeType": "box", "motionType": "static", "mass": 0 } } },
"Wall_N": { "components": { "Physics": { "shapeType": "box", "motionType": "static", "mass": 0 } } },
"Player": { "components": { "Physics": { "shapeType": "capsule", "motionType": "dynamic", "mass": 1, "lockRotation": true } } },

"Ball": {
  "tags": ["ball"],
  "components": {
    "MeshPrimitive": {
      "primitive": "sphere", "diameter": 0.7, "segments": 16, "position": [0, 0.5, 0],
      "material": { "diffuseColor": [0.97, 0.97, 0.97], "emissiveColor": [0.15, 0.15, 0.15] }
    },
    "Shadow": { "castShadow": true, "receiveShadow": false },
    "Physics": { "shapeType": "sphere", "motionType": "dynamic", "mass": 1, "friction": 0.4, "restitution": 0.6 }
  }
}

Add the same static Physics block to Wall_S, Wall_E, and Wall_W. Two fields do most of the work here: shapeType and motionType:

src/components/Physics/Physics.core.ts
export type PhysicsShapeType = 'sphere' | 'box' | 'capsule';
export type PhysicsMotionType = 'dynamic' | 'static' | 'kinematic';

export interface PhysicsBodyOpts {
  shapeType: PhysicsShapeType;
  motionType: PhysicsMotionType;
  mass: number;
  friction: number;
  restitution: number;
  lockRotation: boolean;
  /** Initial world position for the body. */
  posX?: number;
  posY?: number;
  posZ?: number;
}

static bodies never move. They also ignore every collision. That makes them perfect for the pitch and the walls. dynamic bodies follow gravity, mass, and impact. Those are the player and the ball. lockRotation: true keeps the capsule standing upright, so it will not tip over. Under Babylon, all of this runs through Havok. On the ball, restitution: 0.6 sets how much it bounces. friction: 0.4 sets how fast it loses speed on the grass.

Continue reading

Unlock the Full Course

Every lesson, the runnable examples, and the finished build — yours to keep.

$9one-time

Was this page helpful?

We read every note — tell us what's working and what isn't.

↑↓ NavigateEnter SelectEsc CloseCtrl+K Open Search