threejs 点击物体射线检测碰撞

 



<!DOCTYPE html>
<html>

<head>
<title></title>
<style>
canvas {
width: 100%;
height: 100%
}
</style>
<script src="/moban/js/three.js"></script>
</head>

<body>
<script>
document.addEventListener('mousedown', onDocumentMouseDown, false);
function onDocumentMouseDown(e) {
e.preventDefault();
var mouse={};
//将鼠标点击位置的屏幕坐标转成threejs中的标准坐标,具体解释见代码释义
mouse.x = (e.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
//新建一个三维单位向量 假设z方向就是0.5
//根据照相机,把这个向量转换到视点坐标系
var vector = new THREE.Vector3(mouse.x, mouse.y,0.5).unproject(camera);

//在视点坐标系中形成射线,射线的起点向量是照相机, 射线的方向向量是照相机到点击的点,这个向量应该归一标准化。
var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());

//射线和模型求交,选中一系列直线
var intersects = raycaster.intersectObjects(scene.children);
console.log('imtersrcts=' + intersects)

if (intersects.length > 0) {
//选中第一个射线相交的物体
SELECTED = intersects[0].object;
var intersected = intersects[0].object;
console.log(intersects[0].object)
}


}
var camera, scene, renderer;
var mesh;
var geometry;
init();
animate();

function init() {

renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
//
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 500;
scene = new THREE.Scene();


geometry = new THREE.PlaneGeometry(100, 100, 1, 1);
// A begin
geometry.vertices[0].uv = new THREE.Vector2(0, 0);
geometry.vertices[1].uv = new THREE.Vector2(1, 0);
geometry.vertices[2].uv = new THREE.Vector2(1, 1);
geometry.vertices[3].uv = new THREE.Vector2(0, 1);

// A end
// B begin
// 纹理坐标怎么弄
var texture1 = THREE.ImageUtils.loadTexture("/moban/images/tietu.png", null, function(t) {});
var material = new THREE.MeshBasicMaterial({ map: texture1 });
mesh = new THREE.Mesh(geometry, material);
mesh.position.z = 0;
mesh.position.x = 0;
mesh.position.y = 0;
mesh.rotation.x = 0;
mesh.rotation.y = 0;
mesh.rotation.z = 0;
scene.add(mesh);
/* var mesh1 = new THREE.Mesh(geometry, material);
mesh1.position.z = -200;
mesh1.position.x = 100;
mesh1.position.y = -60;
scene.add(mesh1);*/
// B end
// window.addEventListener('resize', onWindowResize, false);
}

function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}

function animate() {

requestAnimationFrame(animate);
// camera.position.z-=1;
renderer.render(scene, camera);

}
</script>
</body>

</html>