Search code examples
vectorcamerathree.jscollisiondirection

Ray.direction where camera (object) is looking at


I am doing simple collision detection and although I can easily detect up/down objects with a THREE.ray, I am having a hard time to find what's in front/back of a camera (or any object) when they rotate? I tried projecting a ray with a projector and to display how that ray shoots using helper arrow. Once I start rotating camera around Y axis, ray points to inverse direction or just acts weirdly...

ray = new THREE.Ray();
projector = new THREE.Projector();
vector = projector.projectVector( coll.getObject().matrix.getPosition().clone(), camera );
ray.direction = vector.normalize();
ray.origin = coll.getObject().matrix.getPosition().clone();
helper.setDirection(ray.direction.clone());
helper.position = ray.origin.clone();

Solution

  • I ended up setting a cube around my object attached to a camera and shooting rays through vertices added up, like this:

    vertices = coll.getObject().geometry.vertices;
            rad = coll.getObject().boundRadius+1;
            var directions = {
                "up": [4,1],
                "down": [6,2],
                "front": [3,4],
                "back": [7,0],
                "left": [5,6],
                "right": [1,2],
            };
            var collisions = {
                "up": {},
                "down": {},
                "front": {},
                "back": {},
                "left": {},
                "right": {},
            };
            for (key in directions){
                (directions[key].length > 1) ? localVertex =  vertices[directions[key][0]].clone().addSelf(vertices[directions[key][1]].clone()) : localVertex = vertices[directions[key][0]].clone();  
                globalVertex = coll.getObject().matrix.multiplyVector3(localVertex);
                directionVector = globalVertex.subSelf( coll.getObject().position );
                ray = new THREE.Ray( coll.getObject().position.clone(), directionVector.clone().normalize(), 0, 1000 );
                intersects = ray.intersectObjects(obj, true);
                if (intersects.length > 0) {
                    distance = intersects[ 0 ].distance;
                    if (distance >= 0 && distance <= rad) {
                        collisions[key] = intersects[ 0 ];              
                    } else {                        
                        collisions[key] = false;
                    }
                } else {
                    collisions[key] = false;
                    ++falseCount;
                }       
            }                   
        }
        return (falseCount !== 6) ? collisions : false;