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.

Coding > 16px Movement

#133480 - Ruben - Fri Jul 06, 2007 11:49 am

Hello all. I just thought that I'd post my solution for this type of movement. All it does is instead of moving 1px per frame, it moves 16px at a time and after it's done it checks again. This is the basic breakdown:

1. You initialize a variable to store how many pixels are left for movement.
Code:
int MovementPixelsLeft = 0;


2. Then, you create a script which updates the movement and pixels, etc.
Code:

//Define Commands
#define MOVE_UP 0x00
#define MOVE_DOWN 0x01
#define MOVE_LEFT 0x02
#define MOVE_RIGHT 0x03
int CommandQueue[4];
int CommandQueueSize = 0;
int i;

//Adds Commands to the Queue
void QueueCommand(u8 WhichCommand) {
 CommandQueue[CommandQueueSize] = WhichCommand;
 CommandQueueSize++;
}

//Update the Variables
void UpdateMovement() {
  if(MovementPixelsLeft <= 0) {
   if(IsKeyPressed(InputPadUp)) {
    for(i=0;i<16;i++) QueueCommand(MOVE_UP);
    break;
   }
   if(IsKeyPressed(InputPadDown)) {
    for(i=0;i<16;i++) QueueCommand(MOVE_DOWN);
    break;
   }
   if(IsKeyPressed(InputPadLeft)) {
    for(i=0;i<16;i++) QueueCommand(MOVE_LEFT);
    break;
   }
   if(IsKeyPressed(InputPadRight)) {
    for(i=0;i<16;i++) QueueCommand(MOVE_RIGHT);
    break;
   }
  }
}

3. Then insert the update script at the beginning of your loop
Code:

int main() {
 for(FrameCount=0;;FrameCount++) {
  UpdateMovement();
  //The Rest of Your Code Goes Here
 }
 return 0;
}

4. Finally, you make a function to handle the commands inserted
Code:

//Execute Commands
void ExecuteCommands() {
 switch(CommandQueue[CommandQueueSize-1]) {
  case MOVE_UP:
   SpriteDirection = 0;
   SpriteCurrentY--;
   break;
  case MOVE_DOWN:
   SpriteDirection = 1;
   SpriteCurrentY++;
   break;
  case MOVE_LEFT:
   SpriteDirection = 2;
   SpriteCurrentX--;
   break;
  case MOVE_RIGHT:
   SpriteDirection = 3;
   SpriteCurrentX++;
   break;
 }
 CommandQueueSize--;
}

5. As a final step, you add this to the bottom of your loop
Code:

int main() {
 for(FrameCount=0;;FrameCount++) {
  UpdateMovement();
  //The Rest of Your Code Goes Here
  ExecuteCommands();
 }
 return 0;
}


That's pretty much it. You just have to define your own function for the 'IsKeyPressed()' and the 'InputPadx'. Hope this helps someone out...

Ruben.