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.

Beginners > sprite coordinates problem

#12689 - ken2 - Sat Nov 22, 2003 7:37 pm

I have a problem involving the sprite flipping upside down when it gets to -1 x on the screen. From what I've heard before, this is a probably a problem with the real coordinates of the sprite, but the funny thing is I'm using a function that looks like it should fix that.. could anyone tell me if anything is wrong with this code? I pass it soanso.x and soandso.y once I have an input check which changes them around.

Code:
void MoveSprite(OAMEntry* sp, int x, int y)
{
   if(x < 0)         
      x = 512 + x;
   if(y < 0)      
      y = 256 + y;

   sp->attribute1 = sp->attribute1 & 0xFE00;
   sp->attribute1 = sp->attribute1 | x;

   sp->attribute0 = sp->attribute0 & 0xFF00; 
   sp->attribute0 = sp->attribute0 | y;
}

#12692 - tepples - Sat Nov 22, 2003 10:08 pm

In your code, what happens when x = -513? Then after your if() statements, the sprite X attribute gets OR'd with -1, and its reflection bits get set. Here's corrected code that makes sure that the coordinates do not affect attribute bits:
Code:
void MoveSprite(OAMEntry* sp, int x, int y)
{
  x &= 0x01FF;  /* chop off high bits no matter how far the sprite goes */
  y &= 0x00FF;

  sp->attribute1 = sp->attribute1 & 0xFE00;
  sp->attribute1 = sp->attribute1 | x;

  sp->attribute0 = sp->attribute0 & 0xFF00; 
  sp->attribute0 = sp->attribute0 | y;
}

_________________
-- Where is he?
-- Who?
-- You know, the human.
-- I think he moved to Tilwick.

#12696 - sgeos - Sun Nov 23, 2003 6:44 am

tepples' solution is better, but here is another one. Replace this code:
Code:
   if(x < 0)         
      x = 512 + x;
   if(y < 0)      
      y = 256 + y;


With this code:
Code:
   while (x < 0)         
      x = 512 + x;
   while (y < 0)      
      y = 256 + y;


-Brendan

#12758 - Mix - Tue Nov 25, 2003 6:50 pm

I noticed this problem in one of the Pern project tutorials, and the way I fixed it was to guarantee that x and y are within the proper range prior to passing them to the MoveSprite function. For example, if the program is checking for the keypad input and then moving the sprite, instead of having:
Code:
if(x < 0)         
      x = 512 + x;

in the MoveSprite function, move it to the place after you check for the left keypad and subtract from x. That way the x in your main program won't ever get to ridiculously low numbers.

I don't mean to say that this way is better, because these other folks have much more experience than me. It just made more sense to me to move the check up front rather than pass "garbage" input to the MoveSprite function. Maybe instead of trying to correct the input, the MoveSprite function should be flagging an exception if it gets bad input coordinates. Can you others comment on this approach?