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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…