Best Practice for separating out components

This is an issue I’ve been trying to figure out myself for quite a while. I agree that belfortk’s suggestion of asset containers works for encapsulating assets but I don’t know if it works as well for the logic.

Babylon is pretty flexible when it comes to how you handle your logic, so I’ve tried three options (no big projects so I’m not sure how any of them scale, also keep in mind that I use TypeScript which means I can’t just add methods to defined Babylon classes):

  • Extending mesh class. Works fine. I’m sure there must be an efficient way to check if a mesh is an instance of your new class but I just iterated over active meshes and checked instanceof. You can sort of take advantage of Babylon’s scene tree with this but I still find it a tad clumsy.

  • ECS. I personally used tick-knock which was a lot of fun and works very well. I find ECS to be pretty logical and declarative. The downside is it’s an external library and it feels like two competing systems (the ECS lib and the Babylon scene tree).

  • Babylon Behaviours & Observables. This one has been my favourite so far though I’m fairly certain it’s not the idiomatic way of using these features. Essentially what I’d do is combine a collection of assets (say meshes that make up a character) under a single parent mesh (you can use an empty mesh like new BABYLON.Mesh('character')) and attach a behaviour to it. In the behaviour I’d add an observer to the onBeforeRenderObservable and that would contain my logic. The nice thing about this is you can attach multiple behaviours (like components) to a mesh and remove them at will.

I’m sure people have much better systems for handling their logic but these have worked for me in the past.

3 Likes