简体   繁体   中英

Simple Chase Game Movement Using Bresenham’s Line Algorithm

I'm creating a game where I'm trying to use Bresenham's line algorithm(http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm ) to have enemies chase a player on a 2D map. The concept of the game is similar to the one found below. The pseudo code below is from http://herselfsai.com/2007/07/simple-predator-prey-chase-algorithms.html

prey current position ( xp, yp )
predator current position ( xP, yP )

x = x position to move to
y = y position to move to
dx = xp – xP
dy = yp – yP
Adx = AbsoluteValue ( dx )
Ady = AbsoluteValue (dy )

if ( xp > xP ) stepX = 1 else stepX = -1
if ( yp > yP ) stepY = 1 else stepY = -1

if ( Ady > Adx ){ //the y distance from prey is larger than the x distance

fraction = 2*dx – dy;

if (( yP != yp ) && ( fraction > 0 )){
x += stepX
}

y += stepY

}else{

fraction = 2*dy – dx;

if (( xP != xp ) && ( fraction > 0 )){
   y += stepY
}

x += stepX
}

Enemies chase the player around the map but the it's ether in 0, 45, 90, etc degree angles and not straight line. Also, in my code the enemies also have random speed(between 0 and 5) and are sometimes over shooting the player, then trying to correct and over shoot again and again. That might be a separate issue.

I sure just not fully grasping the concept of the algorithm. What is the correct way to implement this?

Thanks in advance.

Bresenham's Line Algorithm is an easy to understand and easy to calculate algorithm to make your characters move through a route that's closest to eye to a straight line.

The algorithm will work for your case if cost of going 45 degrees is the same as 90 or 0 degree. Otherwise the route Bresenham takes won't be the fastest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM