Sphere cube intersection test fails

Hi there,

I’ve created this little test at the playground, trying to determine if a sphere and cube intersect:


If they intersect, I want the sphere to be red. Although they clearly don’t intersect, the intersectMesh return true?

What am I doing wrong here?

Check out this documentation page. It should have what you’re looking for.


And here’s an updated version of your playground with the effect I think you were going for:


I think what was happening is that the intersection detection (that’s fun to say) was happening at some point in the scene…perhaps before the rendered change of the position? And once it was set to red, it just never gets set to back.

By putting the hit detection inside the registerBeforeRender call as it demonstrates in the documentation, you essentially assign a material to the sphere before every frame based on whether the intersection is true or false.

Hope that all makes sense.



Thanks PirateJC for confirming what I though: the collision detection has to be done inside the registerBeforeRender call. Perhaps this little detail can be mentioned in the documentation?

I did actually notice that in the example but was hoping it could be done -outside- that call. I am setting up a scene where I need to determine collisions -before- rendering anything on screen (as in: it’s all inside setup code - I’m not rendering anything yet). I guess I will have to look for other solutions in this particular case.

@Jeroen internally calculations based on the position and rotation of meshes are based on their world matrix rather than their properties. The world matrix of a mesh is formed just before rendering not during code interpretation. So as you have the code when the intersection check is carried out both the sphere’s and cube’s world matrices are the identity and so are deemed to be in the same place and hence intersect.

What you need to do is, after setting position, rotation, etc. force the calculation of the meshes’ world matrix with ‘computeWorldMatrix’ before checking intersection, as in https://playground.babylonjs.com/#ATA5VS#2


Ah very nice - I didn’t know that. I’ll experiment with this, thanks!