Jump to content
  • Advertisement
Sign in to follow this  
Sir Sapo

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.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!