我正在尝试在z = 0平面上绘制2D对象,现在我想将屏幕鼠标坐标转换为3D世界坐标。
我用下面的相机:
camera = new THREE.OrthographicCamera(SCREEN_WIDTH / - 2, SCREEN_WIDTH / 2,
SCREEN_HEIGHT / 2, SCREEN_HEIGHT / - 2, NEAR, FAR );
camera.position.set(0,0,500);
camera.lookAt(scene.position);
container = document.getElementById( 'ThreeJS' );
container.appendChild( renderer.domElement );
var floorGeometry = new THREE.PlaneGeometry(1000, 1000, 10, 10);
var material = new THREE.MeshBasicMaterial({color: 0x000000, opacity: 1});
var floor = new THREE.Mesh(floorGeometry, material);
floor.position.set(0,0,0);
scene.add(floor);
targetList.push(floor);
我试过两种方法: 1.答案:[问题]:Mouse / Canvas X, Y to Three.js World X, Y, Z
var vector = new THREE.Vector3();
vector.set(
( event.clientX / window.innerWidth ) * 2 - 1,
- ( event.clientY / window.innerHeight ) * 2 + 1,
0.5 );
vector.unproject( camera );
var dir = vector.sub( camera.position ).normalize();
var distance = - camera.position.z / dir.z;
var pos = camera.position.clone().add( dir.multiplyScalar( distance ) );
但它对我不起作用!pos在3D世界坐标中不是正确的位置;说实话,我实际上并不理解这种方法......
2:
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
var raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(targetList);
// if there is one (or more) intersections
if ( intersects.length > 0 )
{
console.log(intersects[0].point);
console.log("Hit @ " + toString( intersects[0].point ) );
}
这在正常的地方工作,但如果在#ThreeJS div之前添加“width:300px; height:400px”#test div,那么它的位置完全错误,为什么,为什么,为什么?
有人可以给我一个有用的解决方案吗?
答案 0 :(得分:2)
看起来你的视口只覆盖了页面的一部分而不是整个页面,就像所有这些three.js的例子一样。在这种情况下,您需要确定您的实际鼠标坐标有点不同:因此请使用event.offsetX
而不是clientX
。当然,您需要实际的<div>
维度而不是window.innerWidth
var mouse = new THREE.Vector2();
mouse.x = (event.offsetX / SCREEN_WIDTH) * 2 - 1;
mouse.y = - (event.offsetY / SCREEN_HEIGHT) * 2 + 1;