Detecting collisions

So moveWithCollisions will detect when the mesh collides with another, but it doesn’t tell us if and what the mesh collided with. How can we find out?

Looking at the implementation of moveWithCollision, it uses the scene’s collisionCoordinator, with an internal this._internalAbstractMeshDataInfo._meshCollisionData._collider - the mesh.collider property is null.

For example you can add an onCollideObservable callback which will be passed the other mesh…

And this documentation guide shows how you can use the mesh’s action manager instead. :slight_smile:

2 Likes

Thanks, @Blake. The collision trigger is for detecting collisions against specific meshes. The onCollide callback seems more promising, but I don’t want to have to set a callback for every moving thing. Anyway, I found an easier way:

mesh.moveWithCollisions(...)
let collidedMesh = mesh.collider?.collidedMesh
if (collidedMesh) {
    console.debug(`collided with mesh: ${collidedMesh.name}`)
}

Update: Now that I think about it more, the onCollide callback makes sense when you need both meshes to be notified of a collision. For example, a “monster” would use this callback to respond to the player running into it, while a “tree” wouldn’t.

1 Like

I think using the observable works well too in that case, but is a matter of preference… And I never thought of doing it the way you did but LGTM. :slight_smile: :beers:

mesh.onCollideObservable.add((collidedMesh) => {
    console.debug(`collided with mesh: ${collidedMesh.name}`);
});
mesh.moveWithCollisions(...);