Journal 46 — Unity Player Power Up with a Homing Missile!
In this challenge, the player can pick up a homing missile to target the nearest enemy.
This update requires the following:
- New artwork, animation, and power up for a homing missile
- New homing missile game object
- Homing missile script to target the nearest enemy
- Update the Spawn Manager to spawn this new power up
- Update the enemy behavior for when targeted with shields
- Update the UI to display the missiles
For this challenge, I created my own simple artwork and animation in Blender and GIMP.
The missile prefab and the missile power up prefab consist of the following components.
For the homing missile script, we start with a few variables for the player, target, speed, and change in angle speed. In the Start method, we add a reference to the player, start a coroutine to destroy the missile after a few seconds, and get a reference to the missile rigidbody for movement.
For the movement of the homing missile to target, we want to use FixedUpdate instead of Update for physics movement.
The last part of the missile script consists of a coroutine to destroy the missile prefab after a few seconds, and a function to find the nearest game object target.
Over in the Powerup script, we add the new missile power up to call to the player to add the missile power up to its weapons.
In the Spawn Manager script, we can add the missile prefab to instantiate with a small percent chance.
In the Enemy base script, we add an update to the switch statement for the OnTrigger events, with two conditions for when the enemy has a shield or not.
In the Shield script, we need to add a tag for the homing missile to turn off the shields if struck by a missile.
In the Player script, we add the missile power up function to add missiles to inventory, check that the missile count cannot be greater than max storage, and also update the UI. We also need the same script to find the closest enemy as in the homing missile.
In the Player’s Update method, we check for input to instantiate the missile prefab, subtract from inventory, and also update the UI.
For the UI updates, we can follow the same approach as the ship lives. We need a UI image for the missiles and an array of sprites to swap out the missile images as they are used up or added.
The UI update function changes out the image for the missiles in inventory, and also shows and hides the hotkey “v” for firing the missiles when there are some in inventory.
Finally, you can see the results in action!
Thank you for your time!