Now that we have learned how to animate our sprite in a frame-by-frame animation, we will learn how to move a sprite around on our canvas. I want to keep our spaceship animated, but I would prefer it not run in an explosion loop. In our sprites folder, I have included a simple four-stage animation that causes our ship's engines to flicker. The source code is quite lengthy, so I will introduce it in three parts: a preprocessor and global variable section, the show_animation function, and the main function.
Here is the code that defines the preprocessor directives and the global variables at the beginning of our cpp file:
Following the preprocessor directives and global variables, our cpp file contains a show_animation function that defines our game loop. Here is the code for our show_animation function:
void show_animation() { current_time = SDL_GetTicks(); int ms = current_time - last_time;
if( ms >= ms_per_frame) { ++current_frame; last_time = current_time; }
We advance our frame whenever the value in ms, which tracks the milliseconds since the last frame change, exceeds ms_per_frame, which we set to a value of 100. Because the spaceship is moving, we still need to update our canvas every frame with the new spaceship position. We do this by modifying the dest.y value, which tells SDL where to render our spaceship on the y-axis. We subtract one from the dest.y variable every frame to move the spaceship up. We also perform a check to see whether this value has become smaller than -16. Because the sprite is 16-pixels high, this will happen when the sprite has moved entirely off the screen at the top. If this is the case, we need to move the sprite back down to the bottom of the game screen by setting the y value back to 200. In an actual game, to tie our movement directly to the frame rate like this would be a bad idea, but for this demonstration, it will be fine.