I am currently working on a never-ending runner game where a character is positioned at (0,0) and can only move along the X-axis by using arrow keys or the mouse. There are two different types of objects moving from z = -10000
towards the character, and once they reach z = 10000
(i.e., behind the character and offscreen), they are reset back to z = -10000
. To detect collisions between the character and these objects, I am utilizing raycasting code.
The raycasting involves shooting rays from each vertex of the character every frame within the render loop. If these rays intersect with one of the object's vertices at a distance close to the character (the exact distance isn't clear), then a collision is registered.
This is the snippet of my code:
Code running inside the render loop:
detectCollisionRaycaster(character, objectsArray);
Function for collision detection:
let cooldown = false;
let objectMesh;
let collisionResults;
function detectCollisionRaycaster(originObject, collidedObjects) {
let originPoint = originObject.position.clone();
for (var vertexIndex = 0; vertexIndex < objectMesh.geometry.vertices.length; vertexIndex++) {
var localVertex = objectMesh.geometry.vertices[vertexIndex].clone();
var globalVertex = localVertex.applyMatrix4( objectMesh.matrix );
var directionVector = globalVertex.sub( objectMesh.position );
var raycaster = new THREE.Raycaster( originPoint, directionVector.clone().normalize() );
collisionResults = raycaster.intersectObjects( collidedObjects, true );
if ( collisionResults.length > 0 && collisionResults[0].distance < directionVector.length() && !cooldown) {
cooldown = true;
console.info("Object Collided");
setTimeout(function(){
collisionResults.length = 0;
cooldown = false;
}, 500);
}
}
}
The Issue
The collision code triggers multiple times, most likely because the objects are approaching the character causing their vertices to collide with the rays over several frames. This results in the collision code being executed repeatedly as long as the object remains "inside" the character.
Desired Outcome:
I aim for the collision detection code to activate only once, pause collision assessment for a specific duration until there is no more collision with the character, and then resume collision detection.
Attempted Solutions
Initially, I tried implementing a timeout function within the collision-detection code to halt the continuous execution until the specified time elapsed. However, this approach merely caused the code to run once, delay for the timeout duration, and then resume executing the collision detection code for all instances the object was inside the character's space.