Shoot ‘Em Up is a simple shooting game, where you have to survive for as long as possible. Enemies spawn at random locations and move towards you.

Kill them by firing bullets.

This particular game involved a bit of math, especially making the enemies re – orient themselves when the player moves.

## It’s trigonometry time!

Here’s a short of explanation of the math behind that particular feature:

For this game, I’ve written a small 2D Vector class which uses Unit Vector Notation to represent vectors.

Both the player and the Enemies are objects of the particle class. The floating point co – ordinates, and the velocity of a particle are stored as vectors.

The acute angle between the line joining the two particles, and the * x – axis *is given by:

Basically, the enemy must move along this line, if it is to reach the player. When this angle is calculated, the velocity of the enemy may be in some other direction. Our goal now, is to “point” the enemy in the direction of the player without changing his *speed.*

*Speed *is defined as:

The mod() function of the Vector class gives this result. To re-orient the velocity vector along the new θ, keeping it’s magnitude constant, we calculate the new* x* and *y* components as follows:

There is one problem. θ will always be between 0 and π/2. Hence cos θ and sin θ will always be positive. To get around this, we check the sign of Δ*y *and Δ*x. *If Δ*y *is negative, multiply the y component by -1, and if Δ*x* is negative, multiply the x component by -1.

Pointing bullets towards the mouse works in a similar fashion, where the position of the mouse replaces the position of the enemy. Also, the bullet is pointed towards the mouse only at the time of firing.

So there you have it. Application of high school maths and physics in programming. Hope this helped 🙂

Screenshot of the game:

Download the game

Download the source

View the help file