gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > Fixed Point Math? Maybe? Move a sprite from A to B

#107105 - psycorpse - Thu Oct 26, 2006 5:06 pm

I am trying to move a sprite from point A to point B in a diagonal line. Currently as a work around I move the sprite one to the left and one up or what ever direction the sprite is supposed to move in. The problem that I am having is that the direction to the left or right is shorter in distance than the the up or down movement. So it will move diagonal for about half of the way and then it moves up or down. This looks funny and doesn't go well with a card game. So if Fixed point math is what I need to do does anyone have any links to documentation on what I am trying to achieve? I have done a couple of searches on this forum however my results haven't been very successful. I found a couple of threads but nothing really helped.

Thanks,
Psycorpse

#107107 - keldon - Thu Oct 26, 2006 5:48 pm

Use a line drawing algorithm >> http://en.wikipedia.org/wiki/Bresenham's_line_algorithm

#107115 - strager - Thu Oct 26, 2006 8:16 pm

From what I see, you are only moving in a diagonal line (or a strait line, up/down and left/right). You'd want the diagonal movement to seem as fast as the strait movement.

To do this, simply divide the number of pixels moved by the square root of two. If you want to use fixed-point for this, you could do something like:

(Incomplete -- gotta go somewhere...)
Code:
#define FIXSIZE (8)
#define SQRT2FIXED (int)(.. * (1 << FIXSIZE))

u16 pixelx = .. << FIXSIZE, pixely ... << FIXSIZE;

// move
if(diagonal) {
pixelx += SQRT2FIXED;
pixely += SQRT2FIXED;
}


Something like that...

#107124 - psycorpse - Thu Oct 26, 2006 10:10 pm

strager wrote:

(Incomplete -- gotta go somewhere...)
Code:
#define FIXSIZE (8)
#define SQRT2FIXED (int)(.. * (1 << FIXSIZE))

u16 pixelx = .. << FIXSIZE, pixely ... << FIXSIZE;

// move
if(diagonal) {
pixelx += SQRT2FIXED;
pixely += SQRT2FIXED;
}



What does the .. and ... stand for in .. << FIXSIZE, ... << FIXSIZE and in the define?

#107137 - strager - Fri Oct 27, 2006 12:51 am

psycorpse wrote:
What does the .. and ... stand for in .. << FIXSIZE, ... << FIXSIZE and in the define?


Here's some code better explaining what to do:

Code:
#define FIXSIZE (8)
// Should be pre-calculated by your compiler.
#define SQRT2FIXED (int)(1.414213562373095048801688724209698078569671875376948073176679737990 * (1 << FIXSIZE))

void move(u16 *px, u16 *py, direction dir, int amount) {

// Move the sprite
if(direction == diagonal_downright) {
    *px += SQRT2FIXED * amount;
    *py += SQRT2FIXED * amount;
}
else if(dir == up) {
    *py -= amount << FIXSIZE;
}
else // ...
// ...
}

// To get pixel coords from fixed coords, do:
pixelx = px >> FIXSIZE;
pixely = px >> FIXSIZE;


... Or something like that.