florianmaxim
florianmaxim

Reputation: 375

THREE.JS Raycasting to a child of the camera

I have a object (plane) that is a child of the camera so its 'fixed to the screen'.

                plane = new THREE.Mesh(new THREE.PlaneGeometry(10, 10, 10, 10), material);

                plane.position.set(0,0,-5);

                camera.add(plane);

On this plane I have another object which I want to move, to I am sending raycasts to the plane.

                if(INTERSECTED){

                handleEvent();

                raycaster.setFromCamera(mouse, camera);

                var intersects = raycaster.intersectObject( plane);

                if(intersects.length>0){

                    //what is happening here?
                    //these points are definitely not on the plane!


                    var x = intersects[0].point.x;
                    var y = intersects[0].point.y;
                    var z = intersects[0].point.z;

                    INTERSECTED.position.set(x,y,z);

                    console.log(x,y,z);

                }           
            }

The positions on which the rays hit the plane doesn't make any sense for me!

Please help me out, I'm stuck! Thanks!

Here is the fiddle:

jsfiddle.net/74jLjz6q/2

PS: I found this post, with a similar problem, where the camera was a child of another object.. I couldn't find any help for my problem there..

THREE.js Raycasting from a child camera to the scene

Upvotes: 0

Views: 658

Answers (1)

florianmaxim
florianmaxim

Reputation: 375

Okey, I got it by trail and error:

It had to be the other way around (world to local).

I'm not sure if I really understood this..

So, the points are provided in world space. (..Because THREE.Raycaster always does?) And it has to be in local space because the plane is a child of the camera.

Is that right?

(AND I had to substract the distance between the camera and the plane manually.)

 plane.worldToLocal( intersects[0].point );
 INTERSECTED.position.set(intersects[0].point.x,intersects[0].point.y,intersects[0].point.z-5);  

The updated and working fiddle (The cube finally stays on the plane! :) ):

http://jsfiddle.net/74jLjz6q/9/

Upvotes: 1

Related Questions