admin管理员组

文章数量:1429307

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?

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?

Share Improve this question asked Sep 28, 2015 at 19:42 ascallonisiascallonisi 9611 gold badge12 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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 ) {
    //...
}

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./mrdoob/three.js/issues/12231

本文标签: javascriptThreejs select object with camerano mouseStack Overflow