Threejs - Raycast Against Plane 2

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>
<!--

A ray works at world space coordinates. You cannot add a ray inside another mesh, although you can indirectly if you create a setup for maintaing and updating the ray.

When you transform your shape in any way, note that until the render kicks in, the matrix of those objects are not yet truly transformed. This may play a critical role in when you should perofrm a ray cast. Either before or after the transoforms and keep it consistent. Performing raycast before the render kicks in, requires you call updateMatrixWorld on the object to truly update its matrix.

-->

CSS

body {
  margin:0;
}

#hitStatus {
  border:thin solid red;
  padding:3px;
  font-size:18pt;
  font-weight: bold;
  color: red;
}

JavaScript

var scene = new THREE.Scene();

var width = window.innerWidth;
// don't use the full window height
// allow bottom space room for UI button
var height = window.innerHeight * .75;

// renderer and canvas size setup
var renderer = new THREE.WebGLRenderer();
renderer.setSize( width, height );
renderer.setClearColor( 0xcccccc, 1 ); 
document.body.appendChild( renderer.domElement );

// perspective camera - toggle only one on
camera = new THREE.PerspectiveCamera(45, window.innerWidth / height, 1, 10000);
camera.position.set(0, 0, 200);

// ortho camera
// camera = new THREE.OrthographicCamera(-width/2, width/2, height/2, -height/2, 0, 1200);


orthoOrbit = new THREE.OrbitControls(camera, renderer.domElement);
orthoOrbit.screenSpacePanning = true;
scene.add(camera);

// create the scene
faceNormalMesh = new THREE.Mesh();
scene.add(faceNormalMesh);

shapeMesh = createScene();

divHitStatusBox = null;
isWireframe = false;
createUI();

// global raycaster refs
raySphere = null;
raySphereSize = 1;
rayLine = null;
rayLength = 10;
raycaster = new THREE.Raycaster();
var start = new THREE.Vector3(0,0,5);
rayDir = new THREE.Vector3(0,0,-1);
raycaster.set(start, rayDir);

drawRay();
castRay();

function castRay(){
	var intersections = raycaster.intersectObject(shapeMesh);
  if (intersections.length){
    divHitStatusBox.innerHTML = 'hit';
  } else {
  	divHitStatusBox.innerHTML = 'miss';
  }
}

function drawRay(){
	// clean out old meshes
  if (rayLine) { scene.remove(rayLine); }
  
	var ray = raycaster.ray;
	createSphereAtPoint(ray.origin, raySphereSize);
  var lineGeo = new THREE.Geometry();
  var end = ray.origin.clone();
  var shift = ray.direction.clone();
  shift.setLength(rayLength);
  end.add(shift);
  
  lineGeo.vertices.push(ray.origin.clone(), end);
  rayLine = new THREE.Line(lineGeo, new THREE.LineBasicMaterial({color:0x0000ff}));
  scene.add(rayLine);
}

function createLine(start, end){
	var geo = new THREE.Geometry();
  geo.vertices.push(start, end);
  var line =...