# How to create enemy indicator in top down game

Hello,
I am creating a top down game in which player is in the centre of screen and can move in any direction. Enemies are coming randomly from outside of screen towards player. I need to implement an indicator which will indicate that enemy coming. Indicator should always be on the border of camera as well.

While creating an enemy, also create indicator sprite and link enemy and indicator and hide that indicator. After that:
Always rotate indicator towards enemy.
If the enemy distance to the player is less than 100px, show an indicator.

My solution would be method 1, but if you are feeling adventurous try method 2:

You can do it a couple of ways:

1. The easier but have-more-to-do-way is to have 4 hidden border sprites (top, bottom and 2 sides, stretched or tiled) that cover each edge of the screen they represent.
Fire a raycast from the player to the enemy, and use the border as the detection object. Store the raycast collision co-ordinates.
Use the the raycast collision co-ordinates to position the indicator sprite
Rotate the sprite to face the enemy.
Note - Make sure you move the border sprites when the player moves.

1. The harder but a have-less-objects method is to use maths:
From StackOverflow:

The problem reduces to this question: Do two lines from A to B and from C to D intersect? Then you can ask it four times (between the line and each of the four sides of the rectangle).

Here’s the vector math for doing it. I’m assuming the line from A to B is the line in question and the line from C to D is one of the rectangle lines. My notation is that `Ax` is the “x-coordinate of A” and `Cy` is the “y-coordinate of C.” And " `*` " means dot-product, so e.g. `A*B = Ax*Bx + Ay*By` .

``````E = B-A = ( Bx-Ax, By-Ay )
F = D-C = ( Dx-Cx, Dy-Cy )
P = ( -Ey, Ex )
h = ( (A-C) * P ) / ( F * P )
``````

This `h` number is the key. If `h` is between `0` and `1` , the lines intersect, otherwise they don’t. If `F*P` is zero, of course you cannot make the calculation, but in this case the lines are parallel and therefore only intersect in the obvious cases.

The exact point of intersection is `C + F*h` .

Here’s the C code for method 2. It should be fairly easy to convert this into scene variables and do the calculations with that:

``````void intersection(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4)
{
double x12 = x1 - x2;
double x34 = x3 - x4;
double y12 = y1 - y2;
double y34 = y3 - y4;
double c = x12 * y34 - y12 * x34;
double a = x1 * y2 - y1 * x2;
double b = x3 * y4 - y3 * x4;
if(c != 0)
{
double x = (a * x34 - b * x12) / c;
double y = (a * y34 - b * y12) / c;
std::cout << "Intersection point coordinates : \n";
std::cout << "Xin : " << x << std::endl;
std::cout << "Yin : " << y << std::endl;
}
else
{
std::cout << "Lines are parallel";
}
}
``````
2 Likes