SGDK. Sprite animation.

First of all, download the finished project with MEGA.

Next, open resources.res, in this line.

SPRITE sonic_sprite "sonic.png" 6 6 BEST 5

There is a new argument (5). It specifies the time to play a single frame of the animation, in frames. And since the Sega Genesis outputs 60 frames per second, therefore 1 frame will be played 5/60 = 1/12 of a second.

Now, open sonic.png

In this picture, all the animation of the player is stored. We will refer to the animations by the number indicated in the picture above.

Now, open the main.c located in the src folder of your project. Let’s analyze the code.

#define ANIM_STAND 0
#define ANIM_WALK 2

Created 2 constants for easy animation switching.

s16 max_x_spd = 3;
s16 cur_spd_x = 0;

The variables of maximum speed and current. The current speed will be constantly added to the player’s position.

void updateAnim() {
	if(cur_spd_x == 0) {
		SPR_setAnim(sonic_obj, ANIM_STAND);
	} else {
		SPR_setAnim(sonic_obj, ANIM_WALK);
	}
	
if (cur_spd_x > 0) SPR_setHFlip(sonic_obj, FALSE);
        else if (cur_spd_x < 0) SPR_setHFlip(sonic_obj, TRUE);
}

The updateAnim function is called in an infinite while loop.

SPR_setAnim – accepts an object of type Sprite, and the animation number, this function switches animation from the sprite.

So here.

if(cur_spd_x == 0) {
	SPR_setAnim(sonic_obj, ANIM_STAND);
} else {
	SPR_setAnim(sonic_obj, ANIM_WALK);
}

If the player is standing (cur_spd == 0) then, the animation of inactivityis played, otherwise, the animation of walkingis played.

if (cur_spd_x > 0) SPR_setHFlip(sonic_obj, FALSE);
else if (cur_spd_x < 0) SPR_setHFlip(sonic_obj, TRUE);

SPR_setHFlip – rotates the sprite horizontally. That is, here, we turn the sprite in the direction of movement.

Let’s analyze the following handleInput function.

void handleInput(){
  u16 value = JOY_readJoypad(JOY_1);
  cur_spd_x = 0;

if(value & BUTTON_LEFT) {
    cur_spd_x = -max_x_spd;
  } else if(value & BUTTON_RIGHT) {
    cur_spd_x = max_x_spd;
  }
}

I’ve sorted it out here. The only thing here, when you click left/right, the rate is negative/positive. If nothing is pressed, the speed is reset to zero.

Let’s go to the main function in the while loop.

handleInput();
updateAnim();

In the while loop, call the generated functions.

x += cur_spd_x;
if(x > 320-sonic_width)
	x = 320-sonic_width;
else if(x < 0)
	x = 0;
SPR_setPosition(sonic_obj, x, y);

Add speed to the player’s position. Limit the player within the screen. And finally, move the player sprite to the specified position.

Final result.

Пожалуйста отключи блокировщик рекламы, или внеси сайт в белый список!

Please disable your adblocker or whitelist this site!