Three.js,PointerLock和碰撞检测

时间:2013-08-31 10:02:15

标签: three.js collision-detection

我正在开发一个3d虚拟家庭项目。除碰撞检测外,每件事情都很好。 我使用PointerLockControls来进行相机和移动。但我不确定如何在每个可能的方向上发现碰撞。 为简单起见,我开始只是向前和向后碰撞到(0,0,0)上的一个简单立方体:

rays = [
    new THREE.Vector3(0, 0, 1),
    new THREE.Vector3(0, 0, -1)
];

然后:

function detectCollision() {
var vector;
var projector = new THREE.Projector();

for (var i = 0; i < rays.length; i++) {
    var vector = rays[i].clone();
    projector.unprojectVector(vector, camera);

    var rayCaster = new THREE.Raycaster(controls.getObject().position, vector.sub(controls.getObject().position).normalize());
    var intersects = rayCaster.intersectObject(cube, true);

    if (intersects.length > 0 && intersects[0].distance < 50) {
        console.log(vector);
        console.log(i, intersects);
        $("#status").text("Collision detected @ " + rays[i].x + "," + rays[i].z +
            "<br \>" + intersects[0].distance);
    }
}

但是当我接近我的立方体时,控制台会向我显示两条射线都撞到了立方体!所以为什么? 我的光线有问题吗? vector(0,0,1)应该是向后的,而(0,0,-1)应该是向前的,对吗? 在我迷路之前请帮助我! 感谢。

1 个答案:

答案 0 :(得分:8)

最后我发现!!解决方案。我不擅长数学,但最后我明白了 在我从指针锁定器控件获取方向后,依赖于按下哪个键,我将方向放入旋转矩阵以获得实际方向向量(感谢线索Icemonster):

function detectCollision() {
unlockAllDirection();

var rotationMatrix;
var cameraDirection = controls.getDirection(new THREE.Vector3(0, 0, 0)).clone();

if (controls.moveForward()) {
    // Nothing to do!
}
else if (controls.moveBackward()) {
    rotationMatrix = new THREE.Matrix4();
    rotationMatrix.makeRotationY(180 * Math.PI / 180);
}
else if (controls.moveLeft()) {
    rotationMatrix = new THREE.Matrix4();
    rotationMatrix.makeRotationY(90 * Math.PI / 180);
}
else if (controls.moveRight()) {
    rotationMatrix = new THREE.Matrix4();
    rotationMatrix.makeRotationY((360-90) * Math.PI / 180);
}
else return;

if (rotationMatrix !== undefined){
    cameraDirection.applyMatrix4(rotationMatrix);
}
var rayCaster = new THREE.Raycaster(controls.getObject().position, cameraDirection);    
var intersects = rayCaster.intersectObject(hitMesh, true);  

$("#status").html("camera direction x: " + cameraDirection.x + " , z: " + cameraDirection.z);

if ((intersects.length > 0 && intersects[0].distance < 25)) {
    lockDirection();
    $("#status").append("<br />Collision detected @ " + intersects[0].distance);

    var geometry = new THREE.Geometry();
    geometry.vertices.push(intersects[0].point);
    geometry.vertices.push(controls.getObject().position);
    scene.remove(rayLine);
    rayLine = new THREE.Line(geometry, new THREE.LineBasicMaterial({color: 0xFF00FF, linewidth: 2}));
    scene.add(rayLine);
}
}

我还对PointerLockControls.js进行了一些更改,以便在相机碰到对撞机对象时停止移动。我在此处上传了我的示例:CameraRayCasting.zip

<强>更新
最后我找到了一些时间来完成我的TouchControls项目。它使用threejs v0.77.1并支持触摸和命中测试 在这里查看:TouchControls