three.js 2D鼠标单击使用raycaster到3d坐标 [英] three.js 2D mouseclick to 3d co-ordinates using raycaster

查看:121
本文介绍了three.js 2D鼠标单击使用raycaster到3d坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在z = 0平面上绘制2D对象,现在我想将屏幕鼠标坐标转换为3D世界坐标。

I'm trying to draw 2D objects in z=0 plane, now I want to convert screen mouse co-ordinates into 3D world co-ordinates.

I下面的二手相机:

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.答案:[问题]:鼠标/画布X,Y到Three.js世界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 ) );

但这对我不起作用!在3D世界协作中,pos不是正确的位置纵观地说,我实际上并不了解这种方法...

but it does't work for me!the pos is not the correct position in 3D world co-ordinates;To be honestly,I'm not understand this method actually...

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

此功能在正常位置正确,但是如果添加 width:300px; height :400px #ThreeJS div之前的#test div,位置完全错误,为什么,为什么,为什么?

This works right in normal place,but if add "width:300px;height:400px" #test div before #ThreeJS div,it went totally wrong position,WHY,WHY,WHY?

有人可以给我一个可用的解决方案吗?

Could someone give me a usable solution?

推荐答案

像您的视口一样,它只覆盖页面的一部分,而不是整个页面,就像所有三个示例一样。 js。在这种情况下,您需要确定实际的鼠标坐标有些不同:因此,请使用 event.offsetX 而不是 clientX 。当然,您需要实际的< div> 尺寸,而不是 window.innerWidth

Looks like that your viewport covers only a part of the page and not the whole page like in all those examples of three.js. In this case you need to determine your actual mouse coordinates a bit different: so use event.offsetX instead of clientX. And of course you need your actual <div> dimensions instead of window.innerWidth

var mouse = new THREE.Vector2();
mouse.x = (event.offsetX / SCREEN_WIDTH) * 2 - 1;
mouse.y = - (event.offsetY / SCREEN_HEIGHT) * 2 + 1;

这篇关于three.js 2D鼠标单击使用raycaster到3d坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆