In my latest three.js project, I am developing a simple game where the user takes control of a spaceship named playerModel (a Mesh object with a basic BoxGeometry). The objective is to navigate through space while avoiding asteroids (SphereGeometry) that appear in the -Z direction and move towards the ship along the +Z axis.
One crucial function in this project is the detectCollisions function:
// This function checks for collisions between the playerModel and obstacles
function detectCollisions(obstacles) {
var origin = playerModel.position.clone();
for (var v = 0; v < playerModel.geometry.vertices.length; v++) {
var localVertex = playerModel.geometry.vertices[v].clone();
var globalVertex = localVertex.applyMatrix4(playerModel.matrix);
var directionVector = globalVertex.sub(playerModel.position);
var ray = new THREE.Raycaster(origin, directionVector.clone().normalize());
var intersections = ray.intersectObjects(obstacles);
if (intersections.length > 0 &&
intersections[0].distance < directionVector.length()) {
console.log("Collision detected!");
return true;
}
}
return false;
}
During the game loop, I call this method by passing the array "spheres," which contains the asteroid objects:
function draw() {
// continuous drawing loop
requestAnimationFrame(draw);
// render THREE.JS scene
renderer.render(scene, camera);
if (!isGameOver) {
generateSpheres();
handleKey();
movePlayer();
moveSpheres();
if (detectCollisions(spheres))
gameOver();
}
}
The collision detection seems to be functional, however, visually it detects collisions even when the objects are far apart. The ray.intersectObjects method returns intersections with seemingly close distances, even though the actual positions of the objects are quite distant from each other. Additionally, there's a consistent issue with faceIndex being set at 37 for the intersecting asteroid object, which is puzzling considering the variations in radii and segments of the asteroids compared to the small size of playerModel. Any advice or insights would be greatly appreciated!