我正在使用ThreeJs制作太空3D射击游戏。除了碰撞,一切都很顺利。我通过Google在网上找到了一个关于如何检测是否存在冲突但是我找不到任何可以解决我的具体问题的示例。
基本上,如果你把你的船运到一个星球上,船就会停下来。然而,如果你旋转船然后前进撞击地球,你就会导致船被“吸”进地球!
在此处查看我的演示:http://battaglia.homedns.org/webgl/space/ 控制:W,A,S,D分别向上,向左,向下,向右旋转船。 控制:向上,向下,向左,向右移动和转动。
以下是具有冲突检测的特定代码:
function CollisionDetected()
{
if (!shipSphere)
{
return false;
}
var moveDistance = 100 * delta; // 100 pixels per second
var originPoint = shipSphere.position.clone();
if (shipSphere)
{
shipSphere.position.x = ship.position.x;
shipSphere.position.y = ship.position.y;
shipSphere.position.z = ship.position.z;
shipSphere.rotation.x = ship.rotation.x;
shipSphere.rotation.y = ship.rotation.y;
shipSphere.rotation.z = ship.rotation.z;
}
for (var vertexIndex = 0; vertexIndex < shipSphere.geometry.vertices.length; vertexIndex++)
{
var localVertex = shipSphere.geometry.vertices[vertexIndex].clone();
var globalVertex = localVertex.applyMatrix4(shipSphere.matrix);
var directionVector = globalVertex.sub(shipSphere.position);
var ray = new THREE.Raycaster(originPoint, directionVector.clone().normalize());
var collisionResults = ray.intersectObjects(collidableMeshList);
if (collisionResults.length > 0 && collisionResults[0].distance < directionVector.length())
{
if (keyboard.pressed("up"))
{
ship.translateX(-moveDistance*2);
}
else if (keyboard.pressed("down"))
{
ship.translateX(moveDistance*2);
}
}
}
}
答案 0 :(得分:0)
我假设在旋转你的船时,你的一个或多个球体顶点与网格相交。然后,在移动时,碰撞代码会触发,并以错误的方向发送您的对象。
尽量不要旋转碰撞球,而只是你的船。如果球体保持其方向,则在您旋转船舶时不应意外地与任何物体相交。
我做了类似的事情,用立方体作为碰撞对象,它对我来说很好。