Reputation: 941
in a Three.js app I want to get the object that the perspective camera is pointing at and to do that I read the raycaster docs. All the docs that I found talk about doind raycasting with camera and a Vector2 from the mouse coordinates, but I don't want to use the 2d coordinates of the mouse. The camera can rotate for any reason: click and drag the screen, touch control or even VR control, I just want to raycast from the center point of the perspective camera and set as "selected" the object it looks at.
Any suggestions?
Upvotes: 3
Views: 1425
Reputation: 41
The code from Falk still works but Three.js (>r90) requires you to define a target [1]:
target is now required
All you have to do is:
let camera_world_pos = new THREE.Vector3();
let camera_world_dir = new THREE.Vector3();
let raycaster = new THREE.Raycaster();
camera.getWorldPosition(camera_world_pos);
camera.getWorldDirection(camera_world_dir);
raycaster.set(camera_world_pos, camera_world_dir);
let intersects = raycaster.intersectObjects( objectsArray );
if ( intersects.length > 0 ) {
//...
}
[1] https://github.com/mrdoob/three.js/issues/12231
Upvotes: 1
Reputation: 4494
THREE.Raycaster.set()
expects origin
and a direction
vectors:
origin — The origin vector where the ray casts from.
direction — The direction vector that gives direction to the ray. Should be normalized.
Set the cameras world position as origin
and its world direction as direction
:
var raycaster = new THREE.Raycaster();
raycaster.set( camera.getWorldPosition(), camera.getWorldDirection() );
var intersects = raycaster.intersectObjects( objectsArray );
if ( intersects.length > 0 ) {
//...
}
Upvotes: 8