Now we will create an example program to demonstrate a single animated sprite. By keeping the demos short and simple, it’s my belief that the code is easier to understand and learn from. This short program will animate a single explosion, rendering an alpha-transparent targa image at random locations around the screen, as shown in Figure 4.2.
The explosion is composed of 30 128 × 128 sprite frames in a sheet with six columns. Figure 4.3 shows the sprite sheet of the explosion; note the effective use of alpha to produce transparent regions as the explosion dissipates. This shows just how much better alpha is versus the older color-key technology. You can also very easily cause sprites to fade in or out to produce effects such as cloaking or shielding (in the case of a spaceship, for instance). Another popular trick with alpha is to cause a sprite to flicker on and off repeatedly after a collision. One of my favorite tricks is to cycle a sprite’s alpha through the red color component when the sprite “dies.”
Now for the code.
AdviceThe explosion animation was provided courtesy of Reiner Prokein and is available at www.reinerstileset.de. |
#include "..EngineAdvanced2D.h" using namespace Advanced2D; Sprite *explosion; bool game_preload() { g_engine->setAppTitle("SPRITE ANIMATION DEMO"); g_engine->setFullscreen(false); g_engine->setScreenWidth(800); g_engine->setScreenHeight(600); g_engine->setColorDepth(32); return true; } bool game_init(HWND) { explosion = new Sprite(); explosion->loadImage("explosion_30_128.tga"); explosion->setTotalFrames(30); explosion->setColumns(6); explosion->setSize(128,128); explosion->setFrameTimer(40); return true; } void game_update() { int cx,cy; //animate the explosion sprite explosion->animate(); if (explosion->getCurrentFrame() == explosion->getTotalFrames() - 1) { //set a new random location cx = rand()%(g_engine->getScreenWidth()-128); cy = rand()%(g_engine->getScreenHeight()-128); explosion->setPosition(cx,cy); } //exit when escape key is pressed if (KEY_DOWN(VK_ESCAPE)) g_engine->Close(); } void game_end() { delete explosion; } void game_render3d() { g_engine->ClearScene(D3DCOLOR_XRGB(0,0,80)); } void game_render2d() { //draw the current frame of the explosion explosion->drawframe(); }