Skip to content

Instantly share code, notes, and snippets.

@cubicleDowns
Last active December 29, 2015 11:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cubicleDowns/7663532 to your computer and use it in GitHub Desktop.
Save cubicleDowns/7663532 to your computer and use it in GitHub Desktop.
Casting a ray and randomly coloring a cube with THREE.js. See full code here: https://github.com/cubicleDowns/webgl-code-samples
function listeners () {
document.addEventListener('click', castRay, false);
}
function castRay (event) {
event.preventDefault();
var mouse = {};
// since this isn't a full screen app, lets use the dimensions of the container div.
mouse.x = (event.clientX / demo.jqContainer.width()) * 2 -1;
mouse.y = -(event.clientY / demo.jqContainer.height()) * 2 + 1;
var vector = new THREE.Vector3(mouse.x, mouse.y, 1);
demo.projector.unprojectVector(vector, demo.cameras.liveCam);
var ray = new THREE.Raycaster(demo.cameras.liveCam.position, vector.sub(demo.cameras.liveCam.position).normalize());
// Casting a ray to find if there is an intersection.
// Notice I reference an array of the cubes previously added to the scene.
// This is to prevent the ray from intersecting with any non-cube objects.
var intersected = ray.intersectObjects( demo.collisions );
// removing previous click marker
$(".clickMarkers").remove();
// appending a click marker.
demo.jqContainer.append('<div class="clickMarkers" style="pointer-events:none; position: absolute; z-index: 100; left: ' + event.offsetX + 'px; top: ' + event.offsetY +'px">D</div>' );
if(intersected.length > 0) {
// slap a random color on that cube, yo.
intersected[0].object.material.color = demo.setup.randomColor();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment