Collisions in Camera and Meshes

Hello!

I am trying to use collision property. The issue I am facing is… let’s say I created a box and have set the property checkCollisions over this box.

var box = BABYLON.MeshBuilder.CreateBox('main_box',{height: 30, width: 30,depth:30},scene);
box.position.y=14;
box.visibility=0.8;
box.checkCollisions=true;

Inittial position of Universal camera is inside this box. The camera has property like this…

var camera = new BABYLON.UniversalCamera(
  "primaryCamera",
  new BABYLON.Vector3(1, 1, 1),
  scene
);
camera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
scene.collisionsEnabled = true;
camera.checkCollisions = true;
camera.applyGravity = true;
camera.ellipsoid = new BABYLON.Vector3(1, 1, 1);
scene.activeCamera = camera1;
camera.attachControl(canvas, true);
camera.speed = 0.3;

My goal to use this collision property is to restrict camera movement going out of the box.

The issue I am facing is… camera is moving out of the box… collision property is not able to stop the function… though once camera posiotion is out of the box Its not allowing to enter into the box.

Pinging @PolygonalSun

Hey @asheesh,

First of all, welcome to the forums! If I’m understanding what you’re doing, you’re using a box mesh to act as a boundary for your camera. Is that correct? If so, then the reason why it’s not working is because you’re using a solid object as your bounding box. The collision system won’t be able to tell when you’re colliding because the object can’t actually collide with an object until it’s outside of it. A good analogy is that you can’t be prevented from entering a building if you’re already inside that building. When the camera exits the box, the collision detection can now check and prevent the camera from entering.

Since you’re going for the opposite behavior, there are a couple of ways to do it. You could programmatically restrict the camera, which is fine for simple boundaries but I’d recommend building a “fence”. You can use planes or boxes on the outside to act as your boundaries. Here’s an example of that: Camera Bounding Box example | Babylon.js Playground. This is modified form of the collision example found on our Camera Collisions page.

Hopefully, this answers your question but if not, please feel free to reply with any other questions.

1 Like