Homing Missile Part 1
How to create a homing missile
Create a Homing Missile Prefab
Just use a placeholder if you don’t have an image you are satisfied with.
1. Create object with sprite
2. Add component: Rigidbody 2D
3. Add component: Box collider 2D
4. Add a script
5. Prefab it
Pseudocode Homing Missile
As always we start with our logic in pseudocode.
find target — search enemies by tag
get position of target
move towards target
if enemy is hit
then destroy both
Script
To find our target we search by tag. This returns the first enemy found with this function. (Not the closest enemy as is usually the case in games)
void Update()
{
_direction = (_target.transform.position — transform.position).normalized * _speed; transform.Translate(_direction * Time.deltaTime); //self destruct
if (_target.gameObject == null)
{
Destroy(gameObject);
}
}
If does the job, but it doesn’t look/feel that good. That will be covered in our next article.