Original Post
Hi, I am not entirely sure this is the correct forum for what i am about to ask, but here goes. I need to code an "AI" for a "bot" that moves around the world map randomly, but when the distance from him to the player is less or equal than a defined value the will turn to the player and run towards it. I have succeeded in writing something that works, but it has a bug that i do not understand/know how to fix. So i'll leave the code i have here with hope that some one can help me out, or give me a better suggestion The bug that occurs with the code above is that when the guardians are near (not sure of the distance) the player and if the gives a step backward/forward the guardians stop closing in on the player, they seem to be rotating in place. [Edited by - Forkaster on May 22, 2009 5:27:48 AM]
typedef struct guardian
{
double pos_x, pos_y, pos_z;
double look_at_x, look_at_y, look_at_z;
double horizontal_angle;
int HAS_DESTINATION;
double destination_x,destination_z;
}Guardian;
void guardiansMoviment()
{
for(int i=0; i<NUMBER_OF_GUARDIANS;i++)
{
double dist=distanceGuardian(guardians);
if(dist <= DIST_MIN)
{
guardians.destination_x = agent.pos_x;
guardians.destination_z = agent.pos_z;
guardians.HAS_DESTINATION = 1;
}
guardianRandomMoviment(i);
destinationDirection(i);
guadianStep(1,i);
}
}
void guardianRandomMoviment(int i)
{
if(!guardians.HAS_DESTINATION)
{
guardians.destination_x = 3 + rand()/(double)RAND_MAX*(WORLD_WIDTH-6);
guardians.destination_z = 3 + rand()/(double)RAND_MAX*(WORLD_LENGTH-6);
guardians.HAS_DESTINATION = 1;
}
if(distanceGuardianDestination(guardians) <= 0.0)
{
guardians.HAS_DESTINATION = 0;
}
}
void destinationDirection(int i)
{
double difx = guardians.pos_x - guardians.destination_x;
double difz = guardians.pos_z - guardians.destination_z;
double destination_angle = atan2(difx,difz) * RAD;
guardians.horizontal_angle = destination_angle;
guardians.look_at_x = sin(guardians.horizontal_angle);
guardians.look_at_z = cos(guardians.horizontal_angle);
}
void guadianStep(double step,int i)
{
double new_pos_x = guardians.pos_x + step * (guardians.look_at_x);
double new_pos_z = guardians.pos_z + step * (guardians.look_at_z);
guardians.pos_x = CLAMP(new_pos_x,2,WORLD_WIDTH-3);
guardians.pos_z = CLAMP(new_pos_z,2,WORLD_LENGTH-3);
guardians.pos_y = terrainGetInerpolatedHeight(guardians.pos_x,guardians.pos_z) + 1.f;
}