Threejs - Raycaster Detection 2d Custom Shape

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>
<div id="status">
</div>
<p>
One 2d mesh is created with a line outline. the 2nd mesh does ray cast iterating from all its vertices pointing to the next vertice in its array.
</p>
<p>
Raycaster only works with meshes whose face are facing towards the ray. For back side culling, make the mesh have double side. For line, ray cast can hit line in any direction.
</p>
<p>
With raycaster you can control near and far, to put a boundary range of what the ray can detect. Almost like as if a ray cast can cast only to a certain distance.
</p>

CSS

#status {
  border: thin solid red;
  padding:3px;
}

JavaScript

/**
Change uvs on a regular geometry is more tedious than doing it on a BufferGeometry

// to move texture use mesh.material.map.offset.x += .1;

// rotating uvs 45 on regular geometry, a plane with two triangles faces
//face1
geometry.faceVertexUvs[ 0 ][ 0 ][ 0 ].set( 0.5, 1.0 );
geometry.faceVertexUvs[ 0 ][ 0 ][ 1 ].set( 0.0, 0.5 );
geometry.faceVertexUvs[ 0 ][ 0 ][ 2 ].set( 1.0, 0.5 );
//face2
geometry.faceVertexUvs[ 0 ][ 1 ][ 0 ].set( 0.0, 0.5 );
geometry.faceVertexUvs[ 0 ][ 1 ][ 1 ].set( 0.5, 0.0 );
geometry.faceVertexUvs[ 0 ][ 1 ][ 2 ].set( 1.0, 0.5 );  

// rotating uvs 45 on buffer geometry, a plane with two triangles faces
//only have to worry about the 4 points
geometry.attributes.uv.setXY( 0, 0.5, 1.0 );
geometry.attributes.uv.setXY( 1, 1.0, 0.5 );
geometry.attributes.uv.setXY( 2, 0.0, 0.5 );
geometry.attributes.uv.setXY( 3, 0.5, 0.0 );

// the trick though for one sided plane regardless of vertices is to utilize a regular geometry and a buffer geometry. Rotate the vertices from the regular geometry and re-apply the new XY points to the buffer geometries's uvs.

for extruded shapes, UVs will have to be recreated differently, as extruded geos are not buffer geos. It follows a similar pattern, except you have to use the geometry uvs method.
*/
var mod = {};
var objects = []; 
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 35, window.innerWidth/window.innerHeight, 0.1, 15000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0xcccccc, 1 ); 
document.body.appendChild( renderer.domElement );
scene.add(camera);

controls = new THREE.OrbitControls(camera);
setToFullOrbit(controls)
camera.position.copy(new THREE.Vector3(125,125,125));
// fix first frame render issue going invisible
camera.lookAt(new THREE.Vector3(0,0,0));

var axisHelper = new THREE.AxesHelper();
//scene.add(axisHelper);
var gridHelper = createGrid('front', 12);
scene.add(gridHelper);

var...