logo

Babylon.js Market

By Lawrence

5 minutes

Last lesson, the gun fired into nothing. Each shot carries all its details: muzzle point, heading, speed, lifetime, and color. But every shot lands on the bus and vanishes. No system is listening for bulletPool.fire yet. There is an easy fix, but it hides a problem. You could build a new bullet entity and a new sphere mesh on every shot. At fourteen shots a second, that hands the engine dozens of new objects each second. The engine has to allocate them, then garbage-collect them a moment later. All that extra work is what makes a cheap arcade game stutter. This lesson catches those events with a pool instead. The pool allocates once, at boot, and never again.

The World entity: one real component, one empty one

Bullets don't belong to the player or to any enemy. They belong to the whole scene. So the pool that owns them sits on a single World entity. Add it to your scene:

"World": {
  "components": {
    "BulletPool": {
      "poolSize": 48,
      "bulletDiameter": 0.55,
      "color": [1.0, 0.95, 0.35],
      "arenaHalfWidth": 19.5,
      "arenaHalfDepth": 19.5
    },
    "Bullet": {}
  }
}

BulletPool is the real component. Its system registers the pool and answers bulletPool.fire. But Bullet: {} looks broken. It is an empty stub with no fields. It is not a mistake, and you can't leave it out. SceneLoader only starts a system for a component type it sees used at the top level of the scene. The real bullets get built later, at runtime, inside the pool. SceneLoader never sees a Bullet in the JSON. So without this marker, it would never start BulletSystem. Fire the gun then, and a bullet would un-park at the muzzle and just hang there. It would be acquired and placed, but dead, with no system to move it. The empty Bullet: {} is the one line that wakes up the bullet-driving system.

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