Game Development Reference
In-Depth Information
Updating the game loop
Bringing it all together, we should end up with a function like this, which executes
all of our game's behavior:
function update(delta) {
player.update(delta);
checkPlayerCollision(player);
for (var i = bullets.length - 1; i >= 0; i--) {
bullets[i].update(delta);
checkBulletCollision(bullets[i], i);
}
for (var j = 0; j < enemies.length; j++) {
var enemy = enemies[j];
enemy.update(delta);
checkPlayerCollision(enemy);
if (enemy.health <= 0) {
spawn(enemy);
}
shoot(enemy, player);
move(enemy);
}
if (player.health <= 0) {
spawn(player);
}
}
This function calculates all physics (including movement and collision checking),
triggers autonomous behavior such as the bots shooting at targets, and implements
game logic (such as players dying when their health is too low). It is called in every
frame from the animation loop. The delta parameter is the physics time-step, so it
should always be the same value as discussed in the
Timing
section of this chapter.