Threejs - Raycast Linear Test

by black strings

HTML

<script src="https://rawgit.com/mrdoob/three.js/dev/build/three.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/dev/examples/js/controls/OrbitControls.js"></script>
<!--
Note:
- A line with more than 2 points is technically made of up multiple line segment(s)
- A ray cast will look at individual line segements when casting
- Each line segment can only register one intersection
- linePrecision helps determine of a line segment's end points should be consider an intersection if there isn't already an intersection on the line

Forming Triangles:
Need to do a tolerance check on slopes when casting digonally against diagonals due to floating point
-->

CSS

body {
  margin:0;
}

JavaScript

var objects = []; 
var scene = new THREE.Scene();

var width = window.innerWidth;
var height = window.innerHeight * .75;

var camera = new THREE.PerspectiveCamera( 35, width/height, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();

renderer.setSize( width, height );
renderer.setClearColor( 0xcccccc, 1 ); 
document.body.appendChild( renderer.domElement );
scene.add(camera);

controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.screenSpacePanning = true;
setToFullOrbit(controls)
camera.position.copy(new THREE.Vector3(fti(5), fti(5), fti(5)) );
// fix first frame render issue going invisible
camera.lookAt(new THREE.Vector3(0,0,0));

var axisHelper = new THREE.AxisHelper();
scene.add(axisHelper);

var grid = new THREE.GridHelper(fti(12), 12);
grid.rotateX(Math.PI / 2);
scene.add(grid);

// ----- playground starts here ----------------- //

//test lines
var line1 = createLine([new THREE.Vector3(), new THREE.Vector3(10,10,0)]);
var line2 = createLine([new THREE.Vector3(20,12,0), new THREE.Vector3(-10,20,0)]);
var line3 = createLine([new THREE.Vector3(-28, 15, 0), new THREE.Vector3(15,50,0)]);

//ray cast
var raycaster = new THREE.Raycaster();
raycaster.linePrecision = 1;
var origin = new THREE.Vector3(12,0,0);
var direction = new THREE.Vector3(-.9, 1, 0);
direction.normalize();
raycaster.far = 60;
raycaster.set(origin, direction);
var intersections = raycaster.intersectObjects([line1, line2, line3]);
drawRay(raycaster, intersections, 0x0000ff);

//print
var div = document.createElement('div');
document.body.appendChild(div);
print(intersections, div);


// ---- end of playground ---------------------- //
function getSlope(p1, p2){
	return (p2.y - p1.y) / (p2.x - p1.x);
}
function isTriangle(points, div){
	if (points.length === 3){
  
  	// see if we can correct the colinear intersections
    var p1 = points[0];
    var p2 = points[1];
    var p3 = points[2];
    
    var s1 = getSlope(p1,p2);
    var s2 = getSlope(p1,p3);
   ...