@dakom
I’ve been thinking about this issue myself. (Note I’m not a game developer so take this with a grain of salt). My current solution is to use System State Components. You can then ‘save’ the physicsBody
into the component (like they do with the mesh in the example). This is really handy as you can clean up the resource once you’re done (remove it from the world in the case of the physics engine, or detach and dispose of a node in the case of web audio). The Unity docs have a bit of info on these too.
Another possible ‘solution’ is to use a WeakMap to allow you to lookup an object (web audio node, three object3d, a cannon.js body, etc.) keyed by either the entity or the component (I’m still working on this bit to see what effect object pooling has on lookups in WeakMaps). This could look something like the following (note some of this is psudo code, you’ll need to fill it in based on libraries you use and your own style, etc):
class CollidableSystem extends System {
constructor(world, attributes) {
super(world, attributes);
// you can either build the world outside the system
// (if you have multiple systems working on the same
// world graph) or you could build it here if this is the
// only system that needs to deal with it
this.physicsWorld = attributes.physicsWorld;
this.physicsBodiesKeyedByEntity = new WeakMap();
}
execute(delta, time) {
this.queries.toBeAdded.results.forEach(entity => {
// you can take the components you need off the entity
const mesh = entity.getComponent(MeshComponent);
const transform = entity.getComponent(Transform);
// etc..
const physicsBody = generateHullFromMesh(mesh);
physicsBody.copyTransform(transform);
this.physicsWorld.add(physicsBody);
entity.addComponent(CollidableManaged);
this.physicsBodiesKeyedByEntity.set(entity, physicsBody);
});
}
}
These are the two solutions that I’ve come up with. I prefer the system state component approach because you can use queries to fetch items to be disposed of. Its a really nice feature. This is especially true for web audio where you can’t walk the graph to find nodes by name or id like you can in three.js and cannon.js.
Anyway, I hope this helps a bit. If you can find another way to handle these let me know.