我在 THREE.js 库中遇到了碰撞检测问题。下面我找到了我的示例的链接(使用箭头键移动主体对象):
http://jsfiddle.net/flyenet/uJLUU/7/
在此示例中,我想创建自己的几何图形(用于“浮雕”和“主体”)并检测它们之间的碰撞。当身体的顶点位于浮雕内时,左上角的红色方块的不透明度为1,否则为半透明。
身体几何:
var up = new THREE.CylinderGeometry(1, 1, 0.2, 3, 1),
down = new THREE.CylinderGeometry(1, 1, 0.2, 3, 1);
for (var i = 0, l = up.vertices.length; i < l; i++) {
up.vertices[i].x *= 1.75;
up.vertices[i].z = up.vertices[i].z * 0.5;
down.vertices[i].x *= -0.7;
down.vertices[i].z = -down.vertices[i].z * 2.3 + 1;
}
THREE.GeometryUtils.merge(up, down);
浮雕几何:
var geometry = new THREE.CubeGeometry(1, 32, 32, 1, 16, 16);
geometry.applyMatrix(new THREE.Matrix4().makeRotationZ(Math.PI / 2));
for (var i = 0, l = geometry.vertices.length; i < l; i++) {
var x = Math.floor(i / 17),
y = Math.floor(i / 289),
z = i % 17;
geometry.vertices[i].y = y === 0 ? (x - 8) * (x - 8) * 0.1 : -10;
}
检测碰撞情况的功能:
function test() {
var originPoint = body.position.clone();
for (var vi = 0, vl = body.geometry.vertices.length; vi < vl; vi++) {
var localVertex = body.geometry.vertices[vi].clone(),
globalVertex = body.matrix.multiplyVector3(localVertex),
directionVector = globalVertex.subSelf(body.position),
ray = new THREE.Raycaster(originPoint, directionVector.clone().normalize()),
results = ray.intersectObjects([relief]);
if (results.length > 0 && results[0].distance < directionVector.length()) return true;
}
return false;
}
它可以工作,但在某些情况下,当身体位于浮雕的边界并且红色方块是半透明的(而不是不透明度 1)时。它看起来像这样:
这意味着,碰撞检测没有触发。为什么?我应该在代码中进行哪些更改以检测任何碰撞情况?