lundi 9 juin 2008

nds and the atan



Hm, I wanted to shoot an arrow, in the direction in which a sprite is dragged, using the touchscreen of course.
So the arrow sprite has to be rotated, but we have the x distance and the y distance of the dragging.
To get the angle, normally the atan or atan2 is used (this even workd in Second Life!!!)
But apparently not in the nds world...
atan gives an error..... not found in devkitpro???

(ok i know there is no sin or cosin so this could be expected - look up tables is the magic word.)
(where can i find the look-up tables of the atan?)

i searched and found an interesting formula (approximation of the arctan)

((mX + 0.43157974*mX*mX*mX)/(1 + 0.76443945*mX*mX + 0.05831938*mX*mX*mX*mX)/2/PI * 512

ok: the 512 being the "degrees" on the nds ^^

of course this is only valid on domain [-1,1] for mX so we have to shift around the circle a bit....

and finally i got the function working:

int myAtan(float y, float x)
{
if ( fabs(x) > fabs(y) )
{
if (x > 0){
float mX = -y/x;
return (int)((mX + 0.43157974*mX*mX*mX)/(1 + 0.76443945*mX*mX + 0.05831938*mX*mX*mX*mX)/2/PI * 512 + 256+ 128 + 1024) % 512;
//return 0;
}
else
{
float mX = -y/x;
return (int)((mX + 0.43157974*mX*mX*mX)/(1 + 0.76443945*mX*mX + 0.05831938*mX*mX*mX*mX)/2/PI * 512 + 0 + 128 + 1024) % 512;
//return 0;
}
}
else
{
if (y > 0){
float mX = x/y;
return (int)((mX + 0.43157974*mX*mX*mX)/(1 + 0.76443945*mX*mX + 0.05831938*mX*mX*mX*mX)/2/PI * 512 + 256 + 1024) % 512;
return 0;
}else{
float mX = x/y;
return (int)((mX + 0.43157974*mX*mX*mX)/(1 + 0.76443945*mX*mX + 0.05831938*mX*mX*mX*mX)/2/PI * 512 + 0 + 1024) % 512;
}
}
}

yes fabs() is present, haha!

in dragging a sprite around another sprite you get the differences in position x, and y:

distX = touchXY.px - buttonXa; // x position of the dragged sprite - original position
distY = touchXY.py - buttonYa; // the same for the y

stupid enough ( i have to change this) i switched the x an y around in the function call:

int myAngle = (int)myAtan(positionX, positionY);

but it gives the angle and an arrow (giving power by dragged distance) displays the right direction and can be fired by letting go of the dragged sprite....

the dragging of the sprite also posed some problems, which will be documented in another blog...

of course after doing this, i tried the atan again, and it worked......
all written above is discarded, haha!!!