How to detect the collision between camera and mesh without making mesh impenetrable?

If we want a mesh to be available inside of camera.onCollide handler, we can mark the mesh like that:

box.checkCollisions = true;

But this property also makes this mesh impenetrable (camera can’t fly through that mesh). Sometimes it is exactly what we want, but sometimes we want to detect collisions with camera while still allowing a camera to go through.

Is there an easy way to do this in BabylonJS?

A playground for reference:

You could try to check if the camera’s position is inside the mesh Mesh Intersections | Babylon.js Documentation ( This could be done either on the render loop or just when the camera position changes using observables Observables | Babylon.js Documentation ( :slight_smile:


I kind of made it:

But unfortunately, camera doesn’t have onPositionChangeObservable. And it seems like it’s not easy to make a custom one. I was thinking about using something like that

set position(value) {
    super.position = value;
    //notify observers here.

But unfortunately, camera doesn’t re-assign position itself while moving, it’s just altering x, y and z fields of Vector3 inside of position. So, I didn’t find easy way to detect camera position change without re-writing the whole getter and setter (and maybe more stuff) from FreeCamera class.
Right now, I am listening onViewMatrixChangedObservable, which is triggered a bit too often, because it fires on every view change (even when just looking around, without actual position change).
Listening onBeforeRenderObservable/onBeforeStepObservable from scene will give even more unnecessary calls.

Hmmm maybe @PolygonalSun knows of a nice way to listen for changes in the camera’s position?

Ideally, I would like to have some sort of camera.onIntersect function in Babylon.js that would work like camera.onCollide, but with penetrable meshes. I wonder if it’s possible to add this in Babylon.js officially.

TBH, I can’t think of any elegant ways to listen for camera position changes, but you could always check if there are any non-zero values in the camera.cameraDirection vector. The way that our camera works is to add changes there and decrement the values as inertial movements happen.

1 Like

onViewMatrixChangedObservable can help detect any changes on the camera position or orientation

1 Like