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 object.pendingDestroy = true;.
- You will need to prevent the bullet from knocking the asteroid off course by either making the asteroid body ‘immovable’ or giving it a huge mass!
Hints
Set asteroid.body.immovable on the asteroid which is spawned so nothing can alter it’s course (i.e. when bullets hit them).
You will also need to determine whether object1 or object2 is the asteroid in the onAsteroidBulletCollision function you have made by checking the object keys like you did in the “Lives and Death” task.
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 bullet collides with an asteroid, find out whether the asteroid is object1 or object2 in the collision callback by using the “key” property.
- Instead of destroying the asteroid, reduce it’s health by a set amount.
- If the asteroid has zero or less health, then set pendingDestroy = true so that Phaser destroys it at the end of the update.
- In order to make the asteroid keep moving, even when hit by a bullet - set asteroid.body.immovable = true; when spawning the asteroid.