I'm currently working on a project for my master's degree that involves creating a space invaders game using three.js.
While the project is progressing well, I've encountered a problem with my aliens (THREE.Mesh object) being able to fire randomly. I've created a function that successfully generates a random number for this purpose. However, I'm facing an issue with the animate() function. I'm unable to use SetTimeout() within the animate() function.
The SetTimeout() function works the first time animate() is called, but afterward, there is no delay. The code continues to execute without waiting for the timer.
I suspect the problem may be due to animate being constantly called by requestAnimationFrame().
Here's a snippet of my code:
Index.html =>
if (!init()) animate();
function animate(){
requestAnimationFrame(animate);
level1.animate();
render();
}
Level.js =>
Level.prototype.animate = function()
{
//Timer doesn't work
var that = this;
//Just a test with a simple console.log test
setTimeout(function() { console.log("test"); }, 10000);
this.sky.rotation.x -=0.005;
this.spaceship.fire();
for (var i = 0; i < this.ducks.length; i++)
{
this.ducks[i].move();
if (this.ducks[i].is_ready_to_fire())
this.ducks[i].fire_if_ready();
}
};
With this code, the program will wait 10 seconds before printing "test" the first time, but subsequently, it will print "test" without any delay.
Do you have any suggestions on how to fix this issue?
Thank you for your help.
Apologies for any language barriers.