Gatoninja - 8 months ago 37

C++ Question

There is a game in which i have to program the AI and compete with other programers. I am playing that game. It consists in a race, your pod have to pass through some checkpoints in order.

You have some input arguments to use in your algorithm:

`nextCheckpoint (x,y) -> nX,nY`

lastCheckpoint (x,y) -> lnX,lnY

currentposition (x,y) -> x,y

and the output of the code is the directión and the thrust.

`int pod::errorX(){`

int R[2];

int X1;

float b;

int DeltaX;

//Vector of the line between Checkpoints

R[0] = nX-lnX;

R[1] = nY-lnY;

//calculation of the distance in the X axis between the ship and the line

b =(R[0]*(lnX-x) + R[1]*(lnY-y))/((-pow(R[0],2))-(pow(R[1],2)));

X1 = lnY + b*R[0];

DeltaX = x-X1;

cerr<<"Dx: "<<DeltaX<<endl;

return DeltaX;

}

I also have the equivalent pod::errorY()

finally:

`DirectionX = nX-errorX();`

DirectionY = nY-errorY();

Here some pictures of what I am doing:

the theory of what should happen

I want to do this becouse most of the times the inertia make my ship orbitate the checkpoints, this consume a lot of time and makes me loose the race.

Well now let's face the problem, it works sometimes and others is not even close.

When the inputs are small.

like

`nX= 2;`

nY= 2;

lnX=0;

lnY=0;

x=0;

y=0;

The output is:

`directionX = 3`

directionY = 1

But when they are bigger:

`nX= 6553;`

nY= 7817;

lnX=13044;

lnY=1908;

x=13921;

y=3530;

the output:

`DirectionX=6940;`

DirectionY=1907;

I do not know what happen. Maybe becouse b is decimal? is there any error that i havent seen?

Maybe this code is more confortable to test becouse you dont need the game:

`#include <iostream>`

#include <string>

#include <cmath>

using namespace std;

int main()

{

int lnX = 13044;

int lnY = 7817;

int nX = 13044;

int nY = 1908;

int x = 13921;

int y = 3530;

int R[2]={};

//Vector de la recta entre Checkpoints

R[0] = nX-lnX;

R[1] = nY-lnY;

//puro algebra, para calcular el desfase de X

int X1,DeltaX;

long double b;

b =(R[0]*(lnX-x) + R[1]*(lnY-y))/((-pow(R[0],2))-(pow(R[1],2)));

X1 = lnY + b*R[0];

DeltaX = x-X1;

//desfase de y;

int Y1,DeltaY;

Y1 = lnY+b*R[1];

DeltaY = y-Y1;

//dirección

int DirectionX;

int DirectionY;

DirectionX = nX-DeltaX;

DirectionY = nY-DeltaY;

cout<<X1<<" "<<Y1<<endl;

cout<<DeltaX<<" "<<DeltaY<<endl;

cout<<b<<" "<<DirectionX<< " "<<DirectionY<<endl;

Source (Stackoverflow)