Search code examples
three.js3dintersectionraycasting

find upper face of cube on demand


The general problem I'm trying to solve is to find out what face of a cube faces upwards. The cube can be rolled 90° at a time and in any direction. If a certain face faces up, the cube disappears. I'm working with tweens to rotate the cube and change the position of it.

I'm currently trying to solve this by creating a new ray, with its origin set just above the cube and its direction going downwards for a short distance, so it intersects with the upper face of the cube only. violet thingy on top of die is ray cast downward into the cube

So far so good. I get my cube as the object of intersection when I check per console.log(), but as soon as I try to access the face of intersection by faceIntersect.face it seems to be undefined.

Function in question:

function checkUpperFace(posX, posZ) {

  // get position from passed x- and z-values (y is always above cube)
  // and set direction and length of ray
  var position = new THREE.Vector3( posX, 3, posZ );
  var direction = new THREE.Vector3(0, -1, 0);
  var far = 2;
  // create ray, that goes downwards from above the cube
  var cubeRaycaster = new THREE.Raycaster( position, direction, 0, far );
  // get intersection with upper face of rolled cube
  var faceIntersect = cubeRaycaster.intersectObject( currentCube );

  // add a helper to see the ray
  var arrowHelper = new THREE.ArrowHelper( direction, position, far, 0x770077 );
  scene.add( arrowHelper );

  console.log(faceIntersect); // object is shown with everything I want to know
  console.log(faceIntersect.face); // is shown to be undefined

}

Solution

  • Might not be the solution to your raycast problem but another approach: Why don't you simply detect the upper face by comparing the rotation euler angles? E.g. (pseudo code):

    if(cube.rotation.x % 360 == 0)
    {
        // upper face upwards
    }
    else if(cube.rotation.x % 360 == 90)
    {
        // left face upwards
    }
    

    You would have to deal with value tolerance (85° - 95°) negative rotation values and values out of the range of PI*2 but other than that, isn't that much easier?