My Three.js script runs fine when there is only one target div on the page (which holds renderer.domElement). As soon as I add another div with fixed height and width above the target div, ray.intersectObjects returns null. I doubt that the vector that I am creating for ray is causing the problem. Here is the code.
var vector = new THREE.Vector3( ( event.clientX / divWidth ) * 2 - 1, -( event.clientY / divHeight ) * 2 + 1, 0.5 );
projector.unprojectVector( vector, camera );
var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
var intersects = ray.intersectObjects( myObjects, true );
Any ideas on how I can solve this.
EDIT: it is now THREE.Raycaster
(three.js r.56)
The short answer is you have to take into consideration the
offset
of the canvas.The long answer depends on how your code is written, so I'll give you two answers, which should cover the bases.
There are a lot of possible combinations, so you may have to experiment. Also, different browsers may act differently.
Assume your HTML is something like this:
Your JS is something like this:
Method 1 For the following method to work correctly, set the canvas position static; margin > 0 and padding > 0 are OK
Method 2 For this alternate method, set the canvas position fixed; set top > 0, set left > 0; padding must be 0; margin > 0 is OK
Here is a Fiddle if you want to experiment: http://jsfiddle.net/cn7ecoaa/
EDIT: Fiddle updated to three.js r.84
enent.clientX is the client window offset, so to calculate the mouse position we alse have to use the renderer element client window offset. Use the element.getBoundingClientRect() to get the element rect offset the window.
WestLangley, thanks a lot for your explanation. It was really helpful as usual.
In my case, I had my chart in a div absolutely positioned, so I had to do this:
Where rightBlock is my container, that uses only 70% of the screen.
You inspired me and help me solving this problematic issue! Thanks a lot.