I am facing a challenge in my project where I have multiple irregular shapes like triangles, trapezoids, and other custom designs in a 2D scene all located on the Y=0 axis. I am currently working on writing code for collision detection between these shapes.
Since the shapes are complex and not just simple circles or rectangles, I decided to implement raycasting for collision detection.
var raycastCollision = function () {
var originPoint = activeElement.position.clone();
var vertices = activeElement.geometry.vertices;
// Loop through each vertex
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
represents the currently selected shape, while elements
contains a list of all shapes in the scene.
The issue I am encountering is that the collision detection only works in certain scenarios, and I am struggling to identify the specific conditions causing this behavior. However, one thing is clear - it frequently fails to detect collisions when it should.
Can anyone help me pinpoint the error(s) in my code?
Edit: Here are examples of situations where the collision detection does not work properly and where it does: https://i.stack.imgur.com/YBNEM.png