Search code examples
javascripthtmltypescriptbabylonjs

Babylon.js OnIntersectionEnterTrigger not triggering with camera


I'm using Babylon.js 2.4.0.

I have a mesh (in the shape of a couch) loaded from a .obj file, and a camera set up like this:

let camera = new BABYLON.FreeCamera('camera1', new BABYLON.Vector3(0, 2, 0), scene);

camera.checkCollisions = true;
camera.applyGravity = true;
camera.ellipsoid = new BABYLON.Vector3(1, 1, 1);
camera.attachControl(canvas, false);
camera.speed = 0.5;
camera.actionManager = new BABYLON.ActionManager(scene);

I want to set up an event so that when I walk through the couch, "intersection" is logged to the console:

let action = new BABYLON.ExecuteCodeAction(
  { trigger: BABYLON.ActionManager.OnIntersectionEnterTrigger, parameter: { mesh: couchMesh }},
  (evt) => {
    console.log("intersection");
  }
);

this.camera.actionManager.registerAction(action);

When I walk through the mesh, nothing is logged to the console.

I've created an example on the Babylon.js Playground using an example that they provide to check that it wasn't a problem with my mesh or camera set up, and it doesn't appear to be (the playground doesn't work either).


Solution

  • A camera in Babylon.js has no action manager, so even if you set one it won't really work.

    To get this to work using action managers, you could define an invisible box around the camera, with a predefined size and attach the action manager to the mesh created. then set the mesh's parent to be the camera, and you are done. Here is your playground with those changes - http://www.babylonjs-playground.com/#KNXZF#3

    Another solution is to use the internal collision system of babylon js, and set the camera's onCollide function to actually do something :) Here is en example - http://www.babylonjs-playground.com/#KNXZF#4

    Notice that in the second playground, the camera won't go throug the box, as the collision system prevents it from doing so. I am not sure about your usecase, so it is hard to say which one of the two will work better.

    If you need a "gate" system (knowing when a player moved through a gate, for example), use the 1st method. The 2nd is much cleaner, but has its downsides.