Get class which contained the intersecting mesh

Hello! I’m having some kind of structure issue for my game at the moment.

I have a class Player which contain a mesh. I would like to know when my player mesh is intersecting with other meshes such as Coins, PowerUps, etc. Each of the object mentioned above have their own class. In other words, I created a class for Coin and another class for all kind of PowerUps. Each of these classes implements an Interface called ICollectable because I would like to trigger a function in that interface.

I don’t want my player to have any references/dependencies to these collectibles because it would be a nightmare and not really clean. I could check if my player mesh is intersecting with another mesh with this line if I name every collectible mesh “collectible” :

this.mesh.intersectsMesh(this.scene.getMeshByName("collectible"))

or I could simply switch the logic to check if the collectible meshes is intersecting with the player like this :

this.mesh.intersectsMesh(this.scene.getMeshByName("player"))

Anyway, my question is : even if know it is intersecting, how do I access the class related to the intersected mesh? It is a multiplayer game so I need to know which Player is intersecting.

The matter is that if you’ll have a lot of meshes with the same name scene.getMeshByName("collectible") will return only the first mesh with this name.

So the second approach seems to be more reasonable if you have only one mesh with the name ‘player’.

As for classes - do you extend some Babylon classes here or your class just includes mesh as a variable?

Hi @labris !

Oh! I didn’t know that it would return only the first mesh…

Also, since my game is multiplayer, every player has a mesh variable with the name ‘player’. Each 3D object in my game extends a custom class named EntityBase which contained a mesh variable. The Player class also extends the EntityBase class since he is 3D.

Since you’re already using classes, why not have Collectable extend Mesh and Coin, Powerup, etc extend Collectable? That way you can have a static member on on Collectable that’s all the Meshes you want to check for intersection:
Collectable.collectables.filter(c => c.intersectsMesh(…)).forEach(c => c.collectableMethod(…

Also, depending on how you feel about OOP, you might consider having classes that contain a Mesh property extend Mesh instead. This can clean up the code and hen you can also look at the classes in the inspector and add custom properties if it’s helpful.

4 Likes