Archived

This topic is now archived and is closed to further replies.

Krak

Artificial Intellegence?

Recommended Posts

How would one make an enemy constantly walk toward the main character? something like...
if(GuysX < EnemysX)
EnemysX-=0.02f;
else if(GuysX > EnemysX)
EnemysX+=0.02f;
? ...Or what? Help me out a little here.

Share this post


Link to post
Share on other sites
There is a slight flaw, in that if the character and player are not aligned on 0.02f boundaries, when the enemy is lined up with the player, he will move alternately 0.02f left and right, each frame as he approaches the player. Another problem with this method, is that when the enemy is walking diagonally, he moves sqrt(2) times as fast as he does when moving horizontally or vertically. The first problem can be solved as follows:

if( EnemysX > GuysX+0.1f )
EnemysX-=0.02f;
else if( EnemysX < GuysX-0.1f )
EnemysX+=0.02f;

The second problem can be fixed, by dividing the movement into diagonal and non-diagonal vases, and moving him 0.02f at a time non-diagonally, and 0.02f/sqrt(2) (use exact value here) in each axis when moving diagonally.

An even more flexible system is to:

   
if (EnemyX!=GuyX||EnemyY!=GuyY) {
float xv=GuyX-EnemyX;
float yv=GuyY-EnemyY;
float magnitude=sqrt(xv*xv+yv*yv);
if (magnitude>0.02f) {
magnitude*=50.0f; //multiplying by inverse of 0.02f

xv/=magnitude;
yv/=magnitude;
}
EnemyX+=xv;
EnemyY+=yv;
}


I guess what its going on is quite straightforward... I hope it helps anyway, and I didn't make any stupid errors.

EDIT: Slight optimisation

[edited by - dmounty on October 14, 2003 8:49:32 PM]

[edited by - dmounty on October 14, 2003 8:51:38 PM]

Share this post


Link to post
Share on other sites