addEventListener('click',Ray);// 監聽窗口鼠標單擊事件
function Ray() {
var windowX = event.clientX;//鼠標單擊位置橫座標
var windowY = event.clientY;//鼠標單擊位置縱座標
var x = (windowX / window.innerWidth) * 2 - 1;//標準設備橫座標
var y = -(windowY / window.innerHeight) * 2 + 1;//標準設備縱座標
var standardVector = new THREE.Vector3(x, y, 0.5);//標準設備座標
//標準設備座標轉世界座標
var worldVector = standardVector.unproject(camera);
var ray = worldVector.sub(camera.position).normalize();
//創建射線投射器對象
var raycaster = new THREE.Raycaster(camera.position, ray);
//返回射線選中的對象
var intersects = raycaster.intersectObjects(floorChildrenGroup);
console.log(intersects);
if (intersects.length > 0) {
var point=intersects[0].point; //射線在模型表面拾取的點座標
var mesh=intersects[0].object;
}
}
補充一個三維座標轉屏幕座標
function transPosition(position) {
let world_vector = new THREE.Vector3(position.x, position.y, position.z);
let vector = world_vector.project(camera);
let halfWidth = window.innerWidth / 2,
halfHeight = window.innerHeight / 2;
return {
x: Math.round(vector.x * halfWidth + halfWidth),
y: Math.round(-vector.y * halfHeight + halfHeight)
};
}