Reputation: 17141
I am trying to detect clicks on my Plane mesh. I set up a raycaster using the examples as a guide.
Here is the code: http://jsfiddle.net/BAR24/o24eexo4/2/
When you click below the marker line, no click will be detected even though the click was inside the plane (marker line has no effect).
Also try resizing the screen. Then, even clicks above the marker line may not work.
Maybe this has to do with use of an orthographic camera? Or not updating some required matrix?
function onMouseDown(event) {
event.preventDefault();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
//console.log("x: " + mouse.x + ", y: " + mouse.y);
raycaster.setFromCamera(mouse, camera)
var intersects = raycaster.intersectObjects(objects);
if (intersects.length > 0) {
console.log("touched:" + intersects[0]);
} else {
console.log("not touched");
}
}
Upvotes: 4
Views: 2214
Reputation: 168
Try this... It will work anywhere even you have margin and scroll!
function onMouseDown(event) {
event.preventDefault();
var position = $(WGL.ctx.domElement).offset(); // i'm using jquery to get position
var scrollUp = $(document).scrollTop();
if (event.clientX != undefined) {
mouse.x = ((event.clientX - position.left) / WGL.ctx.domElement.clientWidth) * 2 - 1;
mouse.y = - ((event.clientY - position.top + scrollUp) / WGL.ctx.domElement.clientHeight) * 2 + 1;
} else {
mouse.x = ((event.originalEvent.touches[0].pageX - position.left) / WGL.ctx.domElement.clientWidth) * 2 - 1;
mouse.y = - ((event.originalEvent.touches[0].pageY + position.top - scrollUp) / WGL.ctx.domElement.clientHeight) * 2 + 1;
}
raycaster.setFromCamera(mouse, camera)
var intersects = raycaster.intersectObjects(objects);
}
Upvotes: 1
Reputation: 104843
Your CSS will affect your raycasting calculations. One thing you can do is set
body {
margin: 0px;
}
For more information, see THREE.js Ray Intersect fails by adding div.
You also have to handle window resizing correctly. The typical pattern looks like this:
function onWindowResize() {
var aspect = window.innerWidth / window.innerHeight;
camera.left = - frustumSize * aspect / 2;
camera.right = frustumSize * aspect / 2;
camera.top = frustumSize / 2;
camera.bottom = - frustumSize / 2;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
Study the three.js examples. In particular, see http://threejs.org/examples/webgl_interactive_cubes_ortho.html.
Also, read this answer, which describes how to properly instantiate an orthographic camera.
three.js r.80
Upvotes: 6