« Go back

Using of Spritesheets

Now we want to load something animated: a Spritesheet. For example we use an explosion in several states (It's really big, each part is 256x256px): Image

Therefore we need the Surface and Texture structs, which we already know from the previous Tutorial, again. And, instead of the Sprite class, we use the Spritesheet class.

Show Raw
import std.stdio;

import Dgame.Window.Window;
import Dgame.Window.Event;
import Dgame.Graphic;
import Dgame.Math.Rect;

void main() {
    Window wnd = Window(640, 480, "Dgame Test");
    wnd.setVerticalSync(Window.VerticalSync.Enable);
    wnd.setClearColor(Color4b.Black);

    Surface explo_img = Surface("samples/images/explosion.png");
    Texture explo_tex = Texture(explo_img);

    Spritesheet explosion = new Spritesheet(explo_tex, Rect(0, 0, 256, 256));

    bool running = true;
    
    Event event;
    while (running) {
        wnd.clear();
        
        while (wnd.poll(&event)) {
            switch (event.type) {
                case Event.Type.Quit:
                    writeln("Quit Event");
                    
                    running = false;
                    break;
                    
                default: break;
            }
        }
        
        explosion.slideTextureRect();
        
        wnd.draw(explosion);
        
        wnd.display();
    }
}

At first glance, it looks like we are using a Sprite. But there are several alterations: We call the Spritesheet constructor with the Texture and a Rect.

But we draw it as known with wnd.draw(explosion). But there is something new too: the explosion.slideTextureRect(). First things first: the Rect in the Spritesheet constructor tells us which part of the image should be drawn. In this case we start in the upper left corner (coordinates 0|0). As I said above, each part of the explosion is 256x256px, so we set the width and height of the Rect to 256 and 256.

The explosion.slideTextureRect() moves / slides our Rect over the image. We know the size of each part so in each frame the x coordinate is increased by the width of a image part. If the x coordinate is greater than the image width, we set x to 0 and increase the y coordinate to reach the next line. That's all.

Control Animation

« Go back