Public Group

# My AI wont work and I dont know why

This topic is 5397 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I need some help, I wrote this AI code and I think it should work but for some odd reason it wont. First , let me go over how it should work. My game is a 2D topdown shooter and this snippet of code should make the enemies direction(edirections) point towards the players position. If I am being to vague please tell me and I will try and explain it better.
//the x and y arguments are the player x and y position
//x_pos and y_pos are the enemies x and y coordinates
/*edirections is the direction the enemy is pointing and can be an integer between 0 and 15 because there are 16 possible directions*/

void Enemy::dogfightAI(int x , int y)
{
/*angle is the total angle of the enemy, 22.5 is used because it is 360 / 16*/
double angle = (edirections *22.5);

int xs = x - (int)x_pos;

int ys = y - (int)y_pos;
int xd = abs(xs);
int yd = abs(ys);
double tanarg = yd/xd;
double newang = atan(tanarg);
double finalang = newang/22.5;
edirections = finalang;

}



##### Share on other sites
a) trig functions take angles in radians, not degrees (360 degrees = 2pi radians)
b) you are taking the abs of the x and y offsets, thus restricting them to one quadrant only (+x,+y)
c) you should use atan2 instead of atan since atan only returns angles in a half circle range. You'll need to fix point (b) before you use atan2 though.

##### Share on other sites
Thanks , but what is the second argument in atan2? You said I needed a fixed point but I dont understand where to get that from.

##### Share on other sites
atan2's arguments are the y-offset and the x-offset, what you are dividing at the moment.
I wasn't talking about fixed point maths, I meant you would have to address issue (b) that I raised i.e. don't make the x and y differences both positive via abs before using them as the arguments to atan2.

##### Share on other sites
Extra clarification:
atan2(0,1) (x = 1, y = 0) returns 0 radians
atan2(1,0) (x = 0, y = 1) returns pi/2 radians (=90deg)
atan2(1,1) (x = 1, y = 1) returns pi/4 radians (=45deg)
atan2(0,-1) returns pi radians (=180 deg)
etc.

atan2 isn't defined for 0,0 (for obvious reasons).

• 21
• 13
• 9
• 17
• 13