我有8个来自Object3D的射线播放器到不同的方向进行碰撞检测。我想根据物体旋转旋转它们指向的方向。我已经按照here
的解决方案进行了操作raycaster开始旋转但是以一种奇怪的方式。它开始检测来自不同方向的所有光线的碰撞。
在HTML中我有
cube = new THREE.BoxGeometry(1,1,1);
cube_material = new THREE.MeshBasicMaterial({color: 0x00a000});
cube_mesh = new THREE.Mesh(cube, cube_material);
var rays = [
new THREE.Vector3(0, 1, 0), // forward
new THREE.Vector3(0, -1, 0), // backward
new THREE.Vector3(-1, 0, 0), // left
new THREE.Vector3(1, 0, 0), // right
new THREE.Vector3(1, 1, 0), // forward right
new THREE.Vector3(-1, 1, 0), // forward left
new THREE.Vector3(1, -1, 0), // backward right
new THREE.Vector3(-1, -1, 0) // backward left
];
这是我的detectCollision函数,它是从animate()函数调用的:
detectCollision = function( ){
var hit = false;
var dist = 0.8;
var origin = new THREE.Vector3(cube_mesh.position.x, cube_mesh.position.y, cube_mesh.position.z);
var rayHits = [];
for ( var i = 0; i < rays.length; i++){
var matrix = new THREE.Matrix4();
matrix.extractRotation(cube_mesh.matrix);
var dir = rays[i];
dir = dir.applyMatrix4( matrix );
raycaster = new THREE.Raycaster(origin, dir, 0.6, dist);
var intersections = raycaster.intersectObjects(collidable_walls);
if (intersections.length > 0){
// 0 = forward
// 1 = backward
// 2 = left
// 3 = right
// 4 = forward right
// 5 = forward left
// 6 = backward right
// 7 = backward left
switch (i) {
case 0:
console.log("forward: " + i);
cube_mesh.translateY(-0.12);
break;
case 1:
console.log("backward: " + i);
cube_mesh.translateY(0.12);
break;
case 2:
cube_mesh.translateX(0.12);
console.log("left: " + i);
break;
case 3:
cube_mesh.translateX(-0.12);
console.log("right: " + i);
break;
case 4:
console.log("forward right: " + i);
break;
case 5:
console.log("forward left: " + i);
break;
case 6:
console.log("backward right:" + i);
break;
case 7:
console.log("backward left: " + i);
break;
}
}
}
任何人都可以给我一些关于如何正确旋转raycaster的想法,如ArrowHelper(不在图像中工作,但与rotation.z工作得很好)
答案 0 :(得分:1)
使用右手坐标系的Three.js,rays
应为:
var rays = [
new THREE.Vector3(0, 0, -1), // forward
new THREE.Vector3(0, 0, 1), // backward
new THREE.Vector3(-1, 0, 0), // left
new THREE.Vector3(1, 0, 0), // right
new THREE.Vector3(1, 0, -1), // forward right
new THREE.Vector3(-1, 0, -1), // forward left
new THREE.Vector3(1, 0, 1), // backward right
new THREE.Vector3(-1, 0, 1) // backward left
];
在您的函数detectCollision
中,您应该将var dir = rays[i];
更改为var dir = new THREE.Vector3().copy(rays[i])
,或者当您向此dir
应用矩阵时,rays[i]
也会更改。
您最好确保cube_mesh.position
是多维数据集的世界位置。我建议您使用cube_mesh.getWorldPosition()
和cube_mesh.matrixWorld
。