GuRAm
GuRAm

Reputation: 777

Get mouse clicked point's 3D coordinate in three.js

I'm new in THREE.js.

I'm trying to get 3D coordinates of point on mouse click on the object (not simple objects: Box, Sphere,..) in Canvas.

In detail, I'm working with 3D objects viewer - I have camera (THREE.PerspectiveCamera), mouse controls (rotate, zoom, move), add/remove objects (my own object, loaded using loaders for THREE.js) in scene,.. And I want to add a function, which gets 3D coordinates for clicked point in 3D.

Exactly, I want coordinates of the end point of a ray - begining from mouse click on the camera_near_window and ending to the object's point, I've clicked on..

I tried a lot of ways to do it:

Can anyone show me the demo code which gets 3D point coords for clicked point of clicking object in 3D, please..?

Upvotes: 19

Views: 20319

Answers (1)

GuRAm
GuRAm

Reputation: 777

So, as I think this question is useful for someone, I'll answer it myself (I'll write my resolve):

    var renderer, canvas, canvasPosition, camera, scene, rayCaster,  mousePosition;

    function init() {
        renderer = new THREE.WebGLRenderer({ antialias: false });
        canvas = renderer.domElement;
        canvasPosition = $(canvas).position();
        camera = new THREE.PerspectiveCamera(20, $(canvas).width() / $(canvas).height(), 0.01, 1e10);
        scene = new THREE.Scene();
        rayCaster = new THREE.Raycaster();
        mousePosition = new THREE.Vector2();

        scene.add(camera);

        var myObjects = new THREE.Object3D();
        // myObjects.add( your object );
        // myObjects.add( your object );
        // myObjects.add( your object );
        myObjects.name = 'MyObj_s';
        scene.add(myObjects);
    };

    function getClicked3DPoint(evt) {
        evt.preventDefault();

        mousePosition.x = ((evt.clientX - canvasPosition.left) / canvas.width) * 2 - 1;
        mousePosition.y = -((evt.clientY - canvasPosition.top) / canvas.height) * 2 + 1;

        rayCaster.setFromCamera(mousePosition, camera);
        var intersects = rayCaster.intersectObjects(scene.getObjectByName('MyObj_s').children, true);

        if (intersects.length > 0)
            return intersects[0].point;
    };

Upvotes: 25

Related Questions