Unlimited WordPress themes, graphics, videos & courses! Unlimited asset downloads! From $16.50/m
  1. Game Development
  2. Unity 2D

Unity Solution for Hitting Moving Targets

Final product image
What You'll Be Creating

While developing games which involve an action element, we often need to figure out a way to collide with a moving target. Such scenarios can be typically called a 'hitting a moving target' problem. This is particularly prominent in tower defense games or missile command like games. We may need to create an AI or algorithm which could figure out the enemy's motion and fire at it. 

Let's see how we can solve this particular problem, this time in Unity.

1. The Missile Command Game

For this particular tutorial, we will consider a missile command game. In the game we have a turret on the ground which fires missiles at an incoming asteroid. We should not allow the asteroid to hit the ground. 

The game play is tap-based, where we need to tap to aim the turret. With human assistance, the game mechanics are pretty straightforward as the turret just needs to aim and fire. But imagine if the turret needs to automatically fire at incoming asteroids. 

The Challenges for Auto-Firing AI

The turret needs to find out how many asteroids are approaching the ground. Once it has a set of all approaching asteroids, it would then need to do a threat analysis to determine which one to target. A slow-moving asteroid is a lesser threat than a fast-moving one. Also, an asteroid which is closer to the ground is an imminent threat as well. 

These problems can be solved by comparing the speed and position of the incoming asteroids. Once we have determined which one to target, we reach the most complicated problem. When should the turret fire? At which angle should it fire? When should the missile set to explode after firing? The third question becomes relevant because the missile explosion can also destroy the asteroid and has a bigger radius of effect as well.

To simplify the problem, the turret can decide to fire right away. Then we need to only figure out the angle of firing and distance of detonation. Also, there may be the case where the asteroid has already passed the area where it could be hit, meaning there is no solution!

You should download the unity source provided along with this tutorial to see the solution in action. We will see how we derive that solution.

2. The Solution

We are going to do a little refresher of our high school mathematics in order to find the solution. It is very straightforward and involves solving a quadratic equation. A quadratic equation looks like axˆ2 + bx + c = 0, where x is the variable to be found and it occurs with the highest power of 2. 

Analysing the Problem

Let us try to represent our problem diagrammatically. 

diagram of the incoming asteroid and the predicted path of missile

The green line shows the predicted path to be followed by the asteroid. As we are dealing with uniform motion, the asteroid moves with constant velocity. Our turret will need to rotate and fire the missile along the blue path for it to collide with the asteroid at a future time.

For uniform motion, the distance travelled by an object is the product of time and the object's speed, i.e. D = T x S, where D stands for the distance, T is the time taken to travel D, and S is the speed of travel. Assuming that our asteroid and the missiles would definitely collide, we can find the distance of the blue line followed by the missile in terms of time t. In the same time t, our asteroid will also reach the same position. 

Essentially, in the same time t, the asteroid will reach the collision position from its current position, and the missile will also reach the same collision position in the same time t. So at time t, both the asteroid and the missile would be at the same distance from the turret as they would be colliding with each other.

Enter Math

We can equate the distance from the turret to the asteroid and missile at this future time t in order to derive our quadratic equation with the variable t. Consider two points on a two-dimensional plane with coordinates (x1,y1) and (x2,y2). The distance D between them can be calculated using the equation below.

If we denote the turret position as (Tx,Ty), the missile speed as s and the unknown collision position as (X,Y), then the above equation can be rewritten as:

where t is the time taken for the missile to travel the distance D. Equating both, we get our first equation for unknowns X and Y with another unknown t.

We know that the asteroid also reaches the same collision spot (X,Y) in the same time t, and we have the following equations using the horizontal and vertical components of the asteroid's velocity vector. If the velocity of the asteroid can be denoted by (Vx,Vy) and the current position as (Ax,Ay), then the unknown X and Y can be found as below.

Substituting these in the earlier equation gives us a quadratic equation with a single unknown t

Expanding and combining similar terms:

Representing the power of two as ˆ2 and the multiplication symbol as * may have made the above look like hieroglyphics, but it essentially boils down to the final quadratic equation axˆ2 + bx + c = 0, where x is the variable t, a is Vxˆ2 +Vyˆ2 - sˆ2, b is 2* (Vx*(Ax - Tx) + Vy*(Ay - Ty)), and c is (Ay - Ty)ˆ2 + (Ax - Tx)ˆ2. We used the equations below in the derivation.

Solving the Quadratic Equation

To solve a quadratic equation, we need to calculate the discriminant D using the formula:

If the discriminant is less than 0 then there is no solution, if it is 0 then there is a single solution, and if it is a positive number then there are two solutions. Solutions are calculated using the formulas given below.

Using these formulas, we can find values for the future time t when the collision will happen. A negative value for t means we have missed the opportunity to fire. The unknowns X and Y can be found by substituting the value of t in their respective equations.

Once we know the collision point, we can rotate our turret to fire the missile, which would definitely hit the moving asteroid after t secs.

3. Implementing in Unity

For the sample Unity project, I have used the sprite creation feature of the latest Unity version to create the necessary placeholder assets. This can be accessed with Create > Sprites > as shown below.

Implementing in Unity

We have a game script named MissileCmdAI which is attached to the scene camera. It holds the reference to the turret sprite, missile prefab, and asteroid prefab. I am using SimplePool by quill18 to maintain the object pools for missiles and asteroids. It can be found on GitHub. There are component scripts for missile and asteroid which are attached to their prefabs and handle their motion once released.

The Asteroids

Asteroids are randomly spawned at fixed height but random horizontal position and are hurled at a random horizontal position on the ground with a random speed. The frequency of asteroid spawning is controlled using an AnimationCurve. The SpawnAsteroid method in the MissileCmdAI script looks as below:

The Launch method in the Asteroid class is shown below.

As seen in the Update method, once the asteroid has traveled the predetermined distance to ground, deployDistance, it would return to its object pool. Essentially this means it has collided with the ground. It would do the same on the event of collision with the missile.

The Targeting

In order for the auto-targeting to work, we need to call the corresponding method frequently to find and target the incoming asteroid. This is done in the MissileCmdAI script in its Start method.

The FindTarget method loops through all the asteroids present in the scene to find the closest and fastest asteroids. Once found, it then calls the AcquireTargetLock method to apply our calculations.

AcquireTargetLock is where the magic happens as we apply our quadratic equation solving skills to find the time of collision t.

Once we find the point of impact, we can easily calculate the distance for the missile to travel in order to hit the asteroid, which is passed on through the deployDist variable onto the LockOn method of the missile. The missile uses this value to return to its object pool once it has travelled this distance the same way as the asteroid. Before this happens, it would have definitely hit the asteroid, and the collision events would have been triggered.


Once we implement it, the result looks almost magical. By reducing the aiPollTime value, we can make it an invincible AI turret which would shoot down any asteroid unless the asteroid speed becomes close to or higher than our missile speed. The derivation we followed can be used to solve a variety of similar problems which could be represented in the form of a quadratic equation. 

I would like you to experiment further by adding the effect of gravity to the motion of the asteroid and missile. This would change the motion to projectile motion, and the corresponding equations would change. Good luck.

Note also that Unity has an active economy. There are many other products that help you build out your project. The nature of the platform also makes it a great option from which you can better your skills. Whatever the case, you can see what we have available in the Envato Marketplace.

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.