Straight Line Movement
Hi, I'm creating a Predator-Prey game. I need to be able to move the predator in a straight line towards the prey.
So when the prey moves, an imaginary line (which is implemented as a normal line) is created between the predator and prey.
The predator then should move along this line towards the prey.
Any ideas?
Thanks
Dave
[363 byte] By [
daibhada] at [2007-9-28 11:15:25]

Simple math.
You have two points, P1(x1, y1) and P2(x2, y2).
Then you move an object (xa, ya) from P1 to P2 in n steps.
The total horizontal distance is x2 ?x1.
The movement needed in each step, dx, is (x2 ?x1)/n.
dy = (y2 ?y1)/n
xa = x1;ya = y1;
for(int iIdx = 0; iIdx < n; iIdx++)
{
xa += dx;
ya += dy;
}
Use double not int to avoid rounding errors.
u must first get 2 points p1(x1,y1) p2(x2,y2)
.P2( x2, y2)
.
.
.< line
.
.
P1(x1,y1) ................ <-- horizontal line
(y-y1)(x2-x1) =(y2-y1)*(x-x1)
simplify the eq: u get line eq:
then insert from x1 to x2 u get y coodinate
so u can create line
hey look a 3d line pixel steping algorithim
public static final void DrawLineIn3d(int x1,int y1,int z1,int x2,int y2,int z2,int colr,int colg,int colb){
int difx = x2 - x1;
int dify = y2 - y1;
int difz = z2 - z1;
double markx =1;
double marky =1;
double markz =1;
double pdifx = (double)(difx);if(pdifx < 0){pdifx = -pdifx;markx = -1;}
double pdify = (double)(dify);if(pdify < 0){pdify = -pdify;marky = -1;}
double pdifz = (double)(difz);if(pdifz < 0){pdifz = -pdifz;markz = -1;}
int sum = (int)(pdifx + pdify + pdifz);
double dsum = (double)(pdifx + pdify + pdifz);
double ux = pdifx / dsum;// % tot dist x ratio cubic length
double uy = pdify / dsum;
double uz = pdifz / dsum;
ux = Math.sqrt(ux) ;// % aproximate cubic from ratio to positive cubic sin not exact
uy = Math.sqrt(uy) ;
uz = Math.sqrt(uz) ;
double distance = (ux * pdifx) + (uy * pdify) + (uz * pdifz); //sin * length x = distance ? not exactly
ux = pdifx / distance;
uy = pdify / distance;
uz = pdifz / distance;
ux *= markx;uy *= marky;uz *= markz;
int d = (int)(distance);
double ex = 0;
double ey = 0;
double ez = 0;
for(int i =0 ;i< d;i++){
ex += ux;if(ex < -1){ex += 1; x2 --;}
if(ex > 1){ex += -1; x2 ++;}
ey += uy;if(ey < -1){ey += 1; y2 --;}
if(ey > 1){ey += -1; y2 ++;}
ez += ux;if(ez < -1){ez += 1; z2 --;}
if(ez > 1){ez += -1; z2 ++;}
DrawPixel(x2,y2,z2,colr,colg,colb);
}
}//eofmethod