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

前端 未结 1 924
粉色の甜心
粉色の甜心 2021-02-02 15:16

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 wor

1条回答
  •  北荒
    北荒 (楼主)
    2021-02-02 16:17

    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;
    };
    

    0 讨论(0)
提交回复
热议问题