Hamza Díaz
Hamza Díaz

Reputation: 175

C++ How to animate graphics (POO)

I'm working on a game project in c++ using programming oriented object and classes but I can't figure out a way to animate the following graphics.

What I need is while the player is holding left key or the right key, the graphics should be appearing to make the character like moving and when they stop holding the key it'll turn to idle graphic.

I can't paste the whole source code here, i have many classes, and functions.. All I need is a BASIC idea of how to implement it, an example or a function anything useful. I don't need libraries because i just have two sprites to animate so it's not necessary.

As an example be Sprites the class that creates the object and Koala the one that moves it and prints it in a certain position.

Sprites idleSprite, walkingSprite;
Koala koala;

These declarations are just for avoiding other explanations.

enter image description here

I would appreciate your help.

PD: Don't worry about the keyboard keys, or other classes all I need is how to animate a sprite.

Upvotes: 1

Views: 3090

Answers (1)

Christophe
Christophe

Reputation: 73366

Koala should have two states:

  • a direction state: enum Direction {Left,Right};
  • a movement state. enum Movement { Idle, Walk };

As you have only one picture for the walking status, moving graphically the picture around will give the impression of a floating body. I'd recomment that you'd really have at least two walking positions to show that the foots are moving:

  • a movement step counter
  • a constant for the maximum number of steps.

Then the states should be updated in your game loop according to keyboard status and elapsed time. The pseudo code would be something like:

if (!arrow_key_pressed()) {
    status_movement = Idle;
    lasttimer = gametimer();   // keep track of last event 
} 
else {
    status_movement = Walk; 
    if (left_arrow_pressed() ) 
        status_direction = Left; 
    else if (right_arrow_pressed() )
        status_direction = Right; 
    if (gametimer() - lasttimer > 2 ms ) {  // if enough time, 
       if (status_direction==Left) 
          position_x -= step_increment; 
       else if (status_direction==Right)
          position_x += step_increment; 
       movement_step = (movement_step+1) % maxi_steps;
       lasttimer = gametimer(); 
   }
}

All you have then to do is to restore te background of the picture at tis old position, and draw the picture at the position. For this, youd could call a function with paramters position_x, direction, movement status and status step, to return/draw the sprite at the right place.

Upvotes: 3

Related Questions