Animation Demo

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.

Figure 4.2. The AnimationDemo program draws an animated explosion.


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.”

Figure 4.3. The sprite sheet for an animated explosion.


Now for the code.

Advice

The 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();
}

Advice

I have moved the SetIdentity() function call directly into the engine’s main loop because it was redundant in the game code—since it must be set every frame anyway when rendering in 3D. It’s all part of the engine’s evolution!


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset