Reputation: 366
so here's my problem, as i was using three js on a project where user gives x y
coordinates a point is added on a three js scene and i need to calculate the position of the collide object behind/in front of this point. I tried using Raycaster
but I couldn't find a simple example of how to use Raycaster
with a vector defined by point :/
here's my code so far
var projector = new THREE.Projector();
var directionVector = new THREE.Vector3();
/* how could i use a vector defined by my origin point
var origin = new THREE.Vector3(x, y, 0 );
instead of the camera vector as used below ?
*/
projector.unprojectVector(directionVector, camera);
directionVector.sub(camera.position);
directionVector.normalize();
var ray = new THREE.Raycaster();
ray.set(camera.position,directionVector)
var intersects = ray.intersectObjects(scene.children);
if (intersects.length > 0) {
console.log(intersects);
}
Upvotes: 1
Views: 261
Reputation: 104843
To raycast from an arbitrary point, you can use this pattern:
var raycaster = new THREE.Raycaster(); // create once, and reuse
var origin = new THREE.Vector3(); // reuse it
var direction = new THREE.Vector3(); // reuse it
...
origin.set( x, y, z );
direction.set( 0, 0, - 1 ).normalize(); // direction vector must have unit length
raycaster.set( origin, direction );
var intersects = raycaster.intersectObjects( objects, recursiveFlag );
if ( intersects.length > 0 ) {
// your code
}
three.js r.75
Upvotes: 3