Creating a Homing Projectile
Let’s create a new weapon that will target the nearest enemy something like this:
Ok, so the plan is to
- create an array of everything tagged “Enemy” in the projectile (laser) script
- check the locations of each and identify the nearest one
- then adjust the course and rotation of the projectile to intercept.
Basically, FindClosestEnemy() and then TargetClosestEnemy() and we’ll put that in Start() like this:
And in Update, we’ll just need to continuously call the TargetClosestEnemy() so that if our target is destroyed, any projectiles in motion will find new targets.
Notice that we’re going to need a couple of variables to track the GameObject closestEnemy, and the projectile RigidBody rb which we set to our Rigidbody2D Component. Using Rigidbody2D is going to require some extra physics calculations, but will also give us an interesting chase effect.
Let’s look at FindClosestEnemy() first:
We foreach through a comparison of unordered array of game objects and store only the smallest of the comparisons. That becomes our target. We’ll just run this once from Start() to create our list of active targets.
Ok, now let’s look at TargetClosestEnemy(). We’ll run this once from Start() and then continuously from Update() so once an enemy target is destroyed, we’ll auto-retarget the next closest enemy:
Direction is easy, just subtract the projectile position from the closest enemy. Next we use the Vector2 variable since we are working with Rigidbody, and subtract our projectile position from the closestEnemy position. Then we use the z component of a Vector3.Cross to average out the rotation angle and combine that with a speed factor to get our angularVelocity. Now we just give the projectile a velocity in the up direction. This approach gives us a nice arc path instead of a direct point-to-point path.
To tweak the missile spin, we can just adjust the Angular Drag value on the Rigidbody2D until we get the result we want.