Search code examples
three.jsraycasting

Three js raycaster WITHOUT camera


I seem to find only examples to use the raycaster with the camera, but none that just have a raycaster from Point A to Point B.

I have a working raycaster, it retrieves my Helpers, Lines etc. but it seems it does not recognize my sphere.

My first thought was my points are off, so i decided to create a line from my pointA to my pointB with a direction like so:

var pointA = new Vector3( 50, 0, 0 );
var direction = new Vector3( 0, 1, 0 );
direction.normalize();
var distance = 100;

var pointB = new Vector3();
pointB.addVectors ( pointA, direction.multiplyScalar( distance ) );

var geometry = new Geometry();
geometry.vertices.push( pointA );
geometry.vertices.push( pointB );
var material = new LineBasicMaterial( { color : 0xff0000 } );

var line = new Line( geometry, material );

This will show a line from my point (50 0 0) to (50 100 0) right trough my sphere which is at point (50, 50, 0) so my pointA and direction values are correct.

Next i add a raycaster: To avoid conflicts with any side effects i recreated my points here:

var raycaster = new Raycaster(new Vector3( 50, 0, 0 ), new Vector3( 0, 1, 0 ).normalize()); 
var intersects = raycaster.intersectObject(target);
console.log(intersects);

Seems pretty straight forward to me, i also tried to use raycaster.intersectObjects(scene.children) but it gives Lines, helpers etc. but not my sphere.

What am i doing wrong? I am surely missing something here.

IMG of the line and the sphere: enter image description here


Solution

  • What you see is explained in the following github issue:

    https://github.com/mrdoob/three.js/issues/11449

    The problem is that the ray emitted from THREE.Raycaster does not directly hit a face but its vertex which results in no intersection.

    There are several workarounds to solve this issue e.g. slightly shift the geometry or the ray. For your case:

    var raycaster = new THREE.Raycaster( new THREE.Vector3( 50, 0, 0 ), new THREE.Vector3( 0, 1, 0.01 ).normalize() );
    

    However, a better solution is to fix the engine and make the test more robust.

    Demo: https://jsfiddle.net/kzwmoug2/3/

    three.js R106