Skip to content

Instantly share code, notes, and snippets.

@cubicleDowns
Created November 26, 2013 20:16
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/7665436 to your computer and use it in GitHub Desktop.
Save cubicleDowns/7665436 to your computer and use it in GitHub Desktop.
Casting a WebGL ray with an offset.
function init() {
$('#jqv').text($.fn.jquery);
$('#tjsv').text(THREE.REVISION);
demo = new Demo.Scene("ray-intersection");
demo.rotateCamera = true;
listeners();
// start the animation
// this also does all of the setup. i've encapsulated all of this work for brevity.
demo.animate();
}
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.
// OFFSET change. Now I'll adjust the offset of the canvas element from the click.
var leftOffset = demo.jqContainer.offset().left;
var topOffset = demo.jqContainer.offset().top;
mouse.x = ((event.clientX - leftOffset) / demo.jqContainer.width()) * 2 -1;
mouse.y = -((event.clientY - topOffset) / 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 added to the scene.
// This is to prevent the ray from intersecting with any non-cube meshes.
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>' );
// only change the first intersected object.
if(intersected.length > 0) {
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