Asteroid Health
- easy
- Game Development
- JavaScript Objects
At the moment the asteroids die a little too easily. It would be nice if the asteroids had a certain amount of health so that it takes a few hits from bullets to destroy one instead of them dying instantly.
Task Definition
- When an asteroid spawns set a variable on the asteroid to represent it’s health asteroid.health = 100;.
- When a collision occurs, reduce the health on the asteroid asteroid.health -= 100;.
- If the asteroid dies after this collision - grant the player points and set asteroid.destroy();.
Extensions
- When spawning an asteroid, why not spawn one of the different sized asteroids randomly?
- When spawning different sized asteroids - you could give bigger asteroids more health and smaller asteroids less health.
- You could make it so that destroying a large asteroid actually spawns two smaller asteroids!
Walkthrough
- When you spawn the asteroid - set asteroid.health = 100
- When a collision occurs, instead of destroying the asteroid, reduce it’s health by a set amount.
- If the asteroid has zero or less health, then call asteroid.destroy() to actually destroy the asteroid.
Solution
Here is one way that you might solve this task…
Add the following lines of code in MainGameScene.js...
createAsteroid() {
// Existing Code...
asteroid.health = 100;
}
// Your new onAsteroidBulletCollision might look something like this
onAsteroidBulletCollision(asteroid, bullet) {
asteroid.health -= 50;
if (asteroid.health <= 0) {
asteroid.destroy();
this.playerScore += 10;
this.scoreValue.setText(this.playerScore);
}
bullet.destroy();
}