Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Trying to create interactive GUI for my app using threejs. I've found this tutorial: http://zachberry.com/blog/tracking-3d-objects-in-2d-with-three-js/

which explains exactly what I need, but uses some old release.

function getCoordinates(element, camera) {

    var p, v, percX, percY, left, top;
    var projector = new THREE.Projector();
    // this will give us position relative to the world
    p = element.position.clone();
    console.log('project p', p);
    // projectVector will translate position to 2d
    v = p.project(camera);
    console.log('project v', v);

    // translate our vector so that percX=0 represents
    // the left edge, percX=1 is the right edge,
    // percY=0 is the top edge, and percY=1 is the bottom edge.
    percX = (v.x + 1) / 2;
    percY = (-v.y + 1) / 2;

    // scale these values to our viewport size
    left = percX * window.innerWidth;
    top = percY * window.innerHeight;

    console.log('2d coords left', left);
    console.log('2d coords top', top);

}

I had to change the projector to vector.project and matrixWorld.getPosition().clone() to position.clone().

passing position (0,0,0) results with v = {x: NaN, y: NaN, z: -Infinity}, which is not what expected

camera which im passing is camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 )

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
233 views
Welcome To Ask or Share your Answers For Others

1 Answer

function getCoordinates( element, camera ) {

    var screenVector = new THREE.Vector3();
    element.localToWorld( screenVector );

    screenVector.project( camera );

    var posx = Math.round(( screenVector.x + 1 ) * renderer.domElement.offsetWidth / 2 );
    var posy = Math.round(( 1 - screenVector.y ) * renderer.domElement.offsetHeight / 2 );

    console.log( posx, posy );
}

http://jsfiddle.net/L0rdzbej/122/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...