I am working on an FPS game. You can see it deployed on Heroku here (it takes almost ten seconds to load so please wait).
The player can shoot properly but the enemies can’t, even though they’re using the same logic.
Bullets get saturated just after the shooting function is called. I need the enemy to shoot the bullets with some suitable delay, just like happens when the player is shooting.
Here is my code.
bulletTempEnemy = new J3D.Transform();
bulletTempEnemy.geometry = J3D.Primitive.Sphere(0.5, 4, 4);
bulletTempEnemy.renderer = J3D.BuiltinShaders.fetch("Normal2Color");
bulletHolderEnemy = new J3D.Transform();
engine.scene.add(bulletHolderEnemy);
function EnemyShooting(){
bulletHolderEnemy.position.x =swat2.position.x;
bulletHolderEnemy.position.y =swat2.position.y;
bulletHolderEnemy.position.z =swat2.position.z;
var b = bulletTempEnemy.clone();
var f =v3.sub(first_person_controller.position,swat2.position).norm();
b.direction = new v3();
b.direction=f;
b.position.fromArray(f);
b.progress = 0;
b.ttl = 50;
b.animate = function() {
b.position = b.direction.cp().mult(1 + b.progress);
b.progress += 1;
b.ttl--;
if(b.ttl == 0) {
bulletHolderEnemy.remove(b);
}
}
bulletHolderEnemy.add(b);
}
The code below was called in the game loop function draw():
var zdis= Math.abs(Math.abs(Math.abs(swat2.position.z) - Math.abs(first_person_controller.position.z)));
var xdis= Math.abs(Math.abs(Math.abs(swat2.position.x) - Math.abs(first_person_controller.position.x)));
if(xdis < 80)
{
setInterval(EnemyShooting(), 90000);
}
for(var i = 0; i < bulletHolderEnemy.numChildren; i++) {
bulletHolderEnemy.childAt(i).animate();
}
I’m using the J3D library.
For waiting a certain amount of time before calling a function, see https://developer.mozilla.org/en/docs/DOM/window.setTimeout
To stop the enemy shooting bullets, you should use
clearInterval.Note that with your current code, if you’re calling
setInterval(EnemyShooting(), 90000);continuously in an update method things will continue to create more “timers” – you may only need one.