我得到了一个具有多个随机形式的场景(如三角形,梯形,还有更多自定义设计),我试图编写用于碰撞检测的代码。形状都是2D,位于Y=0
由于表格比圆形和矩形更复杂,我决定使用光线投射来检查碰撞。
var raycastCollision = function () {
var originPoint = activeElement.position.clone();
var vertices = activeElement.geometry.vertices;
//loop
for (var vertexIndex = 0; vertexIndex < vertices.length; vertexIndex++) {
var localVertex = vertices[vertexIndex].clone();
var globalVertex = localVertex.applyMatrix4(activeElement.matrix);
var directionVector = globalVertex.sub(activeElement.position);
var ray = new THREE.Raycaster(originPoint, directionVector.clone().normalize(),true);
ray.ray.direction.y = 0;
var collisionResults = ray.intersectObjects(elements);
debug["ray" + vertexIndex] = ray;
if (collisionResults.length > 0 && collisionResults[0].object != activeElement && collisionResults[0].distance < directionVector.length()) {
debug["raycast detection"] = "HIT";
break;
}
}
}
ActiveElement
是当前选定的形状,elements
是场景中所有形状的列表。
我遇到的问题是它只能检测到&#34;命中&#34;在某些情况下,我还没有能够确定在什么情况下。但有一件事是肯定的:通常情况下,它不会在应有的时候发现命中。
任何人都可以检测到我的代码中的错误吗?
答案 0 :(得分:1)
由于我的旧答案不正确,我将其删除了。
我在测试场景中尝试了您的功能,以下解决方案有效:
https://jsfiddle.net/qzL9L38a/
我猜问题就是你的情况下的平行面。
对于球体,以下作品:
var raycastCollision = function () {
var originPoint = spheres[0].position.clone();
var vertices = spheres[0].geometry.vertices;
//loop
for (var vertexIndex = 0; vertexIndex < vertices.length; vertexIndex++) {
var localVertex = vertices[vertexIndex]; // no need to clone if applyMatrix4 won'T change localVertex.
var globalVertex = localVertex.applyMatrix4(spheres[0].matrix);
var directionVector = globalVertex.sub(originPoint);
var ray = new THREE.Raycaster(originPoint, directionVector.clone().normalize(),true);
var collisionResults = ray.intersectObjects(spheres);
collisionResults = collisionResults.filter(function(element)
{
return element.distance < directionVector.length();
});
if (collisionResults.length > 0 ) {
console.log('HIT: '+collisionResults);
break;
}
}
}