Issue with intersectsBox

Hey guys,

I am doing simple collision in a project using intersectsBox. All game obstacles have hitboxes which are cubes, and the player has one as well.

In my update loop I am doing the following:

  detectCollision(object1, object2){

    var box1 = new Box3(new THREE.Vector3(), new THREE.Vector3());

    var box2 = new Box3(new THREE.Vector3(), new THREE.Vector3());
    return box1.intersectsBox(box2);


I am also when each obstacle is created computing their bounding boxes and updating their matrix worlds. I put these outside of my detection to avoid doing those in my update loop.

So the issue is, it seems like everything returns true for hitting my player when it is placed for the first time. It seems like some kind of race condition. I have been able to sort of hack around this, but the root cause I am uncertain of and keeps springing up. It seems like when I place a new object it automatically thinks it is hitting the player, even though it is nowhere near the player. So like my computeBoundingBox or updateMatrixWorld is not finishing before its checking for collision?

Thanks guys!

It’s actually not necessary to call this method over and over again. You should ensure that your bounding box is computed once via:


and then it’s sufficient to do:

box1.copy( object1.geometry.boundingBox ).applyMatrix4( object1.matrixWorld );

This code assumes that the geometry is static and the world matrix is up to date. You should always call updateMatrixWorld() before checking for collisions. Not only when adding new objects to your scene but also with existing ones.

Besides, do not create instance of Box3 every time you execute detectCollision(). Create the objects once and then reuse them.

1 Like

Thank you very much for clearing this up! I was able to fix my issue by added a Z check to the player, since this is an infinite runner type of game. I will circle back and modify how I’m handling the bounding box!