Thursday, July 29, 2010

Sprite animation from sprite sheet in Qt

In my previous post I have shown how to create simple sprite animation, but in that sample code I was using different image for each animation sequence.
But most of time we need to work with sprite sheet( image which has all animation sequence) and we need to perform animation using sprite sheet.

In following code I has have done sprite animation using sprite sheet. Trick here is to draw only certain portion of whole pixmap using QPainter's drawPixmap API.

My code goes as below
class Sprite
{
public:

    Sprite();

    void draw( QPainter* painter);

    QPoint pos() const;

    void nextFrame();

private:

    QPixmap* mSpriteImage;
    int mCurrentFrame;
    QPoint mPos;
    int mXDir;

};

Sprite::Sprite():mPos(0,0),mCurrentFrame(0)
{
    mSpriteImage = new QPixmap(":dragon.png");
}

void Sprite::draw( QPainter* painter)
{
    painter->drawPixmap ( mPos.x(),mPos.y(), *mSpriteImage, 
                                   mCurrentFrame, 0, 100,100 );
}

QPoint Sprite::pos() const
{
    return mPos;
}

void Sprite::nextFrame()
{
    //following variable keeps track which 
    //frame to show from sprite sheet
    mCurrentFrame += 100;
    if (mCurrentFrame >= 500 )
        mCurrentFrame = 0;
    mPos.setX( mPos.x() + 10 );
}

Sprite sheet used for above code is as follow.

1 comment:

  1. Could you be more specific with this tutorial? I have no idea how to use this code in Qt Creator, because:

    1. What kind of project can run this? Qt Widget Application or Qt Console Application etc ?

    2. Does that code go into header or main.cpp etc?

    ReplyDelete