Wednesday, May 18, 2011

Sprite animation from sprite sheet using QML

Recently I was going through my old code, found code for sprite animation from sprite sheet. I wondered how same can be done with QML.

After little playing with QML and little bit of google. I came up with following code.

Following code is for my sprite QML element in Sprite.qml file. Here main trick is to use clip property of Item element. Which clips own painting, as well as the painting of its children, to its bounding rectangle.

Item{
    id:sprite
    clip: true
    property alias running: timer.running;
    property int frame:0
    property int frameCount: 0;
    property alias source:image.source

    Image{
         id:image
         x:-sprite.width*sprite.frame
     }

    Timer {
        id:timer
        interval: 200; running: false; repeat: true
        onTriggered: {
            nextFrame();
        }
    }

    function nextFrame() {
        sprite.frame = ++sprite.frame  % sprite.frameCount
    }
}

Following code shows how we can use above code.
Rectangle {
    width: 400
    height: 100

    Sprite {
        x:150
        width: 64;height: 64
        source: "dragon.png"
        running: true
        frameCount: 5
    }
}

Following is demo from above code.

4 comments:

  1. Hi, nice blog you have here. I have a question about animation. The problem is I'm using multiple images (as if extracted frames from GIF) instead of sprite sheet. So what is the best solution to make it animate with different frame speed? For example, you want to make the frame go slower (500ms) and then make the frame faster (100ms).

    ReplyDelete
    Replies
    1. lol, nevermine, I just figure it out. Just combine the extracted images as a single sprite sheet and use it like yours. Thanks for the great post. =^__^=

      Delete