Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast a visible ray threejs

Tags:

three.js

I want to aim for objects with cameras' vision (as the user would look at the object, not point at it with mouse).

I'm casting a ray from the camera like this

rotation.x = camera.rotation.x;
    rotation.y = camera.rotation.y;
    rotation.z = camera.rotation.z;
    raycaster.ray.direction.copy( direction ).applyEuler(rotation);
    raycaster.ray.origin.copy( camera.position );

var intersections = raycaster.intersectObjects( cubes.children );

This gets me the intersections but it seems to wander off sometimes. So I'd like to add aim (crosshair). That would be somekind on object (mesh) at the end or in the middle of the ray.

How can I add it? When I created a regular line it was in front of the camera so the screen would go black.

like image 439
Noripsni Avatar asked Jul 27 '15 14:07

Noripsni


1 Answers

You can add a crosshair constructed from simple geometry to your camera like this:

var material = new THREE.LineBasicMaterial({ color: 0xAAFFAA });

// crosshair size
var x = 0.01, y = 0.01;

var geometry = new THREE.Geometry();

// crosshair
geometry.vertices.push(new THREE.Vector3(0, y, 0));
geometry.vertices.push(new THREE.Vector3(0, -y, 0));
geometry.vertices.push(new THREE.Vector3(0, 0, 0));
geometry.vertices.push(new THREE.Vector3(x, 0, 0));    
geometry.vertices.push(new THREE.Vector3(-x, 0, 0));

var crosshair = new THREE.Line( geometry, material );

// place it in the center
var crosshairPercentX = 50;
var crosshairPercentY = 50;
var crosshairPositionX = (crosshairPercentX / 100) * 2 - 1;
var crosshairPositionY = (crosshairPercentY / 100) * 2 - 1;

crosshair.position.x = crosshairPositionX * camera.aspect;
crosshair.position.y = crosshairPositionY;

crosshair.position.z = -0.3;

camera.add( crosshair );
scene.add( camera );

Three.js r107

http://jsfiddle.net/5ksydn6u/2/


In case you dont have a special usecase where you need to retrieve the position and rotation from your camera like you are doing, I guess your "wandering off" could be fixed by calling your raycaster with these arguments.:

raycaster.set( camera.getWorldPosition(), camera.getWorldDirection() );
var intersections = raycaster.intersectObjects( cubes.children );

Cast visible ray Then you can visualize your raycast in 3D space by drawing an arrow with the arrow helper. Do this after your raycast:

scene.remove ( arrow );
arrow = new THREE.ArrowHelper( camera.getWorldDirection(), camera.getWorldPosition(), 100, Math.random() * 0xffffff );
scene.add( arrow );
like image 59
Falk Thiele Avatar answered Sep 30 '22 14:09

Falk Thiele