gpt4 book ai didi

三.js、PointerLock和碰撞检测

转载 作者:行者123 更新时间:2023-12-02 19:45:51 25 4
gpt4 key购买 nike

我正在开发一个 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);
}
}

但是当我足够接近我的立方体时,控制台显示两条光线都击中了立方体!所以为什么?我的光线有问题吗?矢量(0,0,1)应该向后,(0,0,-1)应该向前,对吧?请帮助我,以免我迷失在 3D 中!谢谢。

最佳答案

我终于发现了!!解决方案。我数学不好,但最后我明白了。
在我从指针锁控件获得方向后,根据按下的键,我将方向放入旋转矩阵中以获得实际的方向向量(感谢 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

关于三.js、PointerLock和碰撞检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18546875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com