feat: Systems API to add/replace systems like physics, collisions, broadphase, spatial queries, etc
Originally wrote by @mflerackers:
Systems allow users to replace existing systems or introduce new ones. A system is a process which works on a certain subset of entities. For example a collision system works on area/body entities, while a physics system works on body entities. spatial partioning works on areas. First a spatial partioning system works as a broad phase to create a set of collision candidates. Then the collision system checks more thoroughly whether any pair of candidates collides. Finally the physics system calculates the new positions. The spatial partitioning system also helps to quickly find objects under the cursor, within a region or within the screen (to skip drawing objects outside the screen).
testPlugin(k: KaboomCtx) {
const verlet = {
fixedUpdate() { // Called at fixed intervals, for example 1/60th of a second
// Calculate velocity, update positions
// Calculate constraints
}
}
let qt
const quadtree = {
add() {
qt = new QuadTree()
},
objectAdded(obj: GameObj<any>) { // Called when an object is added
qt.insert(obj)
},
objectChanged(obj: GameObj<any>) { // Called when an object changes position or size
qt.update(obj)
},
objectRemoved(obj: GameObj<any>) { // Called when an object is removed
qt.remove(obj)
},
objectsAt(rect: Rect): GameObj<any>[] { // Called for hover or collision candidates
return qt.query(rect)
}
}
k.addSystem("Physics", verlet)
k.addSystem("SpatialPartitioning", quadtree)
}