Showing posts with label animation. Show all posts
Showing posts with label animation. Show all posts

Sunday, May 3, 2015

Color Animation using Animator with Unity3D

I created a small demo application to demonstrate how Animation can be done using Animator and State Machine with Unity5. This demo creates a Blinking Animation on Mouse click.

Following is final output of this demo.


Below post shows, how above animation can be created.

-> To begin, First create a simple cube and apply a material on the cube. Setup should look like below.

-> Then using "Add Component", add Animator to this cube.

-> Once Animator is added, open Animation window using "Window" -> "Animation", We will need to use while performing the animation.


Animator performs animation using State Machine and this state machine should have default state. Animator will transit to this default State when object is created. In Animator, Animation clip is considered as a State, so lets add a Animation clip and name it default.


-> Our default state will not have any animation, it should show just initial color. Let's just add one frame with current color. Like below.


-> Now we have default state, let's add another state which will perform "Blinking" animation.



-> Now we should add frames, so let's add color property and frames to animate color.




After adding these frames color should animate like below.



-> Now we have Blinking animation state, we are now ready to create a State Machine. Open Animator window by clicking on "Animator" object, it should look like below.

-> We should now add a Parameter which will be used to Trigger animation. On "Animator" window add new boolean parameter and name it "blink".



Following video shows how to create transition and how to add condition to those transition.


-> Now we have state machine with transition and condition, but we want Blink Animation to terminate once its finished. Let's open "Blink Animation" and add Animation event line shown in below image.


This will prompt you to select function to be invoked when Animation frame is reached. You can select function from attached Script.


Following video shows the same process.



-> Finally, We also need to add a script to Cube object. Following is code for the script. In script we are setting "blink" transition parameter of Animator to true on mouse click. While StopAnimation sets "blink" parameter to false when animation event is called.

using UnityEngine;
using System.Collections;

public class MyAnimation : MonoBehaviour {

 private Animator animator;

 void Awake() {
  animator = GetComponent ();
 }

 void OnMouseUp() {
  startAnimation ();
 }

 public void startAnimation() {
  animator.SetBool ("Blink", true);
 }

 public void stopAnimation() {
  animator.SetBool ("Blink", false);
 }
}

And now if run project and click cube, you should see blink animation as per demo video. That's it hope this post will be helpful.

Friday, July 4, 2014

Creating simple fade animation with Unity3D

I recently used fade animation or opacity animation with one of my Unity game, it was used to fade then earned points during game play. Initially I struggled a bit to achieve opacity animation due to confusion between using Animation or Animator. Look like from Unity version 4.3 we need to use Animator to animate the properties. I was trying to use Animation instead of Animator, was not able to perform opacity animation properly.
In this post I will show, how I accomplished the Fading animation. below is video of final effect and whole process to achieve animation.
First create a initial setup of scene. Following is how my scene looks like.

I wanted to add fading effect to 3D text, which signifies the points earned during game play. Now scene looks like below.

Now we need to add animator component to text.

Now, that we have added animator, we can go to Animation windows and setup our first key.

First key is from where our animation will start, we need to setup second key where animation will end. Create a second key at desired location and move text at appropriate location.

I also wanted to animate opacity with size and location. So lets add new curve for color animation.

Setup the opacity value for color curve for both first key and second key. Following is how my keys looks like.


Now if you press play button or play animation you will be able to see fade animation. Thanks for reading my blog.

Friday, February 21, 2014

Creating Parallax effect in Unity 4.3 2D game

I was checking out Unity3D's 2D workflow and I seen the were able to implement Parallax effect for game background without much effort.

In this post I will show I they achieved parallax effect without single line of code for Unity2D game.

Final effect looks like shown in below video.

First, I created a sample project in 2D mode and imported Sky background in asset and created a sky game object.

This is how it looks after importing Sky background.


I wanted to show clouds moving in the sky, so I created image with clouds and imported those to Unity. Now we need to create a two sprite of cloud image and put those side by side. Once that is done we need to animate both cloud background such that at end of animation second could background image is at the place of first cloud background.

To make this movement process easy, we will create a empty game object and name it Clouds.


Now we will create two object of cloud background image and place those image under empty gameobject which we just created.


We need to arrange those side by side, like below.


We can move Clouds object( the empty gameobject) and both cloud object will move together. This empty gameobject make things easier for movement and its easy way to group object together.

So, now we are ready to make parallax animation, first make sure Animation window is visible, you can make it visible like shown in blow pic.


Select the Clouds empty gameobect, we need to create initial key for animation, which is our current default position.


Once initial animation key is created, right click on time on timeline and select add key, it will add animation key, now you can move Clouds game object to create animation. This key is out intermediate animation key.


Finally, we need to add final animation key, right click on another time on timeline and add key, and move Clouds gameobject such that second cloud image is at place of first one.


We are done, now if you press play button you can see cloud moving continuously as shown in video.

Sunday, December 15, 2013

Importing Mesh and Animation from 3D Studio Max to Unity3D

In past some post I tried to show how we can perform 2D animation and collision detection.

In this post I am will show I we can import 3D mesh with animation created from 3D studio max to Unity3D and animate the same.

So lets start, I created a sample mesh with animation with 3D Studio max.


We need to export it using FBX file format, which we can easily import in Unity3D.


To import it, you can drop the created FXB format file to Asset folder in Unity3D. Once you import it click imported mesh to display its property in Inspector window. In Inspector window click on Rig tab and set animation type to Legacy.

This is required else animation will not play and you will get error "Animation needs to be marked as Legacy"




Now we can use this mesh and perform animation, you can also change its property like play automatically or loop animation.


Now lets add a script, which make model jump when pressing some button.


And here is script.
using UnityEngine;
using System.Collections;

public class JumpAnimation : MonoBehaviour {

 // Update is called once per frame
 void Update () {
  if(  Input.anyKeyDown ) {
   animation.Play("Jump");
  }
 }
}

So now its ready,if you press any button now, it should jump. Here is video how it looks.

 

Saturday, November 9, 2013

Collision detection with Unity3D

So by now I know how to do animation and object creation in Unity3D. Now I started to learn how to get collision detection working with Unity3D.

In Unity3D collision is detected by using various collider objects. Box collider should work for most 2D games. There are some other shapes collider also available, but that I am not going to discuss here.

So to start, I created a basic setup, one egg and one cube which will act as wall and all I want it notification when egg collides the wall.



Now we have scene setup, so for egg to be able to detect collision, go to Box Collider in inspector, and select Is Trigger option. By selecting Is Trigger, egg can move through wall but still gives us notification of collision. In this post I am going to work with Trigger only.



For collision detection to work in Unity3D, atlest one of object needs to be rigid body. so lets add rigid body to egg.



Now we are ready, lets add script which makes egg move. script looks like below.
using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {
 
 private int frame;
 
 // Use this for initialization
 void Start () {
  frame = 0;
 }
 
 // Update is called once per frame
 void Update () {
 
  //skipping some frame to make animation look smooth
  if( Time.frameCount % 10 != 0 ) {
   return;
  }
  
  //makeing it move
  transform.position += new Vector3((-5.0f * Time.deltaTime), 0.0f, 0.0f);
  
  //sprite animation
  frame++;
  if( frame > 8 ) {
   frame = 0;
  }
  renderer.material.mainTextureOffset = new Vector2(frame*0.125f,0);
 }
 
}
Now if you run the game, you can see egg moving but to be able to detect collision we need to add following functions to the script.
 
        void OnTriggerEnter(Collider other)
 { 
  Debug.Log("Collision enterd:" + other.gameObject.name );
 }
  
 void OnTriggerExit(Collider other)
 {
  Debug.Log("Collision exited:" + other.gameObject.name );
 }

Now if you run the game, you can see logs printed when egg pass through wall. Here is how it works.

We can also detect collision with empty game object as well.Just add empty game object to scene and add Box Collider to it. That's It should work just the same.

 

Saturday, January 12, 2013

Sprite animation from sprite sheet with BB10 Cascades QML

In past I have posted solution for how to achieve sprite animation from sprite sheet with Qt C++ widget framework and with QML framework.

I tried to do the same with BB10 Cascades QML. Final output will look like below.


While it was quite straight forward to achieve this with Qt or QML, with Cascades you will need to tweak few things, like desabling the implicit Cascades animation and enabling cliping.

Following is my code for the dragon sprite.

        Container {
            id: sprite;
            preferredHeight: 100;
            preferredWidth: 100;
            clipContentToBounds: true
            horizontalAlignment: HorizontalAlignment.Center
            verticalAlignment: VerticalAlignment.Center
            layout: AbsoluteLayout {}  
            
            onCreationCompleted: {
                timer.timeout.connect(renderNextFrame);
                timer.start(200);
            }
                        
            function renderNextFrame() {
                dragonSprite.currentFrame = 
                      (dragonSprite.currentFrame + 1) % dragonSprite.frameCount;
                dragonSprite.translationX = 
                     -(dragonSprite.currentFrame * sprite.preferredWidth);
            }
                              
            ImageView{
                id: dragonSprite
                imageSource: "dragon.png"
                scalingMethod: ScalingMethod.AspectFill
                preferredHeight: 100
                preferredWidth: 500 
                property int currentFrame: 0
                property int frameCount: 5
                
                attachedObjects: [
                    ImplicitAnimationController {
                        propertyName: "translationX"
                        enabled: false
                    }
                ]  
            }
        }
First, I am creating parent Container which will hold ImageView with sprite sheet as image source.

We need enable clipping by setting clipContentToBounds to true so only certain portion of image is visible not whole image and also need to set preferredHeight, preferredWidth to indicate clip region.

Then I am attaching the renderNextFrame function with timeout signal. renderNextFrame takes care of which frame to display by changing current frame and translating the image view accordingly.

Second, I am creating ImageView with sprite sheet image as image source. We need to set scalingMethod to ScalingMethod.AspectFill so that unnecessary scaling is not performed. Again we need to set preferredWidth, preferredHeight so that proper frame is displayed.

I am also storing max frame count and current frame number with image.

And finally we need to disable the implicit animation for translationX property. Without this you will not be able to achieve smooth sprite animation. We can use ImplicitAnimationController element to disable implicit animation. However it allows only certain property to be disabled. Here is documentation about ImplicitAnimationController.

Once this is done, you will be able to see smooth animation.

Sunday, July 17, 2011

Swipe to unlock animation effect using QML

Now its raining heavily here and that provided me some free time to play with my iPod. As I was using my iPod I got curious about how that "swipe to unlock" animation could have been implemented.

I decided to implement such animation my self with QML and following is output of my effort.



If you also curious about how it can be implemented, than solution is quite simple.
The code is similar to code for Marquee text animation. To give marquee text effect, I used to change position of text element only. Here I change position of both text and parent Item element.

Here is full code. In code I created one static text in gray color which is fully visible and another text with white color which is partially visible only ans used for scrolling animation. I put this animating text inside Item element.

Now on timer event, I am increasing x position of Item element with some delta , at same time I am also reducing same delta from text x position. This will give effect as color or gray static text is changing.

import QtQuick 1.0

Item {
    id:marqueeText
    height: staticText.height
    clip: true    
    property int tempX: 0
    property alias text: staticText.text
    Text {
        x:0;y:0        
        id:staticText
        width: marqueeText.width
        color: "darkgray"
    }

    Item {
        width: 40
        height: marqueeText.height
        x: tempX
        clip: true
        Text {
            id:scrollingText
            text: marqueeText.text
            color: "white"
        }
    }

    Timer {
        id:timer
        interval: 200; running: true; repeat: true
        onTriggered:{            
            tempX = tempX + 10
            scrollingText.x = -tempX;

            if( tempX > staticText.width ) {
                tempX=-40
            }
        }
    }
}
Here is how above code can be used.
Rectangle {
        border.width: 2
        border.color: "black"
        color:"gray"
        anchors.horizontalCenter: parent.horizontalCenter
        width: 200
        height: text.height + 10
        y:100
        ScrollText {
            id:text
            width: 150
            anchors.verticalCenter: parent.verticalCenter
            anchors.horizontalCenter: parent.horizontalCenter
            text: "Swipe to unlock the phone"
        }
    }

That's all. Hope you enjoyed it.

Friday, May 27, 2011

Some QML animation technique

I wanted to learn QML's animation so I thought of creating simple game which use lots of animation effect. I will soon update more detail about game itself when I finished it. But for now I wanted to share whatever I learned by creating my simple QML based game.

Following are some handy animation code, which I created while creating game.

Controlling Animation from Function and using sequential animation.

In following code, I have created a standalone sequential animation and controlling that animation from animate function.
import Qt 4.7

Rectangle {
    id: window
    width:  200
    height: 400
    
    SequentialAnimation {
        id: anim
        property string color: "lightgreen"

        PropertyAnimation {
            target: window
            properties:"color"
            to: anim.color
            duration:100
        }

        PauseAnimation { duration: 100 }

        PropertyAnimation {
            target: window
            properties:"color"
            to: "darkgreen"
            duration:100
        }
    }
    
    MouseArea {
        anchors.fill: parent
        onClicked: {
            animate();
        }
    }

    function animate() {
        anim.color = "lightgreen"
        anim.running = true;
    }
}

Starting animation on property change.

Following code perform Behavior animation on smallRect when ever we change its x value. Behaviour animation can also be applied on other property like width, height, color etc...
smallRect.x = 200

  Rectangle {
        color: "blue"
        id:smallRect
        width: 100;height: 200;
        x:100;y:50;

        Behavior on x { PropertyAnimation { duration: 1500 } }
  }


Performing animation on component creation.

If you want to perform animation when component is created then you can put animation code inside Component.onCompleted method like following. This code is more useful if you are creating animation dynamically on runtime. If have created QML element statically then you might want to perform animation when opacity changes.

Component.onCompleted : {
        animate();
    }

Performing animation on component destruction.

Following code perform animation when object is destroyed. Like above code this is also more useful when object is constructed and destroyed at runtime.

Animation is performed when we call remove function. Remove function will start opacity change animation and when animation is complete it will destroy parent QML animation.
Rectangle {
        color: "blue"
        id:smallRect
        width: 100;height: 200;
        x:100;y:50;

        NumberAnimation {
            id:removeAnim
            target:smallRect
            properties:"opacity"
            to:0
            duration:1000
            onRunningChanged: {
                if(running == false ) {
                    smallRect.destroy();
                }
            }
        }

        function remove()
        {
            removeAnim.running = true;
        }
    }

Pausing and resuming animation.

Following code demostrate how to pause and resume animation. We can control animation by using running property of animation.
    MouseArea {
        anchors.fill: parent
        onClicked: {
            //animate();
            if( anim.running == false ) {
                //starting animation
                anim.running = true;
            } else {
                //pausing animation
                anim.running = false;
            }
        }
    }

I hope above code is helpful.

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.

Tuesday, March 22, 2011

Getting Animation start ,stop event in QML

While working on my hobby QML Project, I required to detect when particular animation got completed

Well its quite simple to achieve this but initially I struggled with it, I was trying to use onCompleted signal to detect animation end, but latter realised that it comes from component and not from animation.

Actual signal we want to use is onRunningChanged and we can check animation's running property to decide if animation is started or ended. Following is my sample QML code to detect Animation start and stop.
Behavior on rotation {
        PropertyAnimation {
            id: rotAni;
            duration: 500 ;
            onRunningChanged: {
                if (!rotAni.running) {
                    console.log("Animation completed");
                } else {
                    console.log("Animation started");
                }
            }
        }
    }
As requested in comment, I am posting similar example for NumberAnimation as well.
Rectangle {
        width: 360
        height: 360

        gradient:first
        Gradient {
            id:first
            GradientStop { position: 0.0; color: "red" }
            GradientStop { position: 0.33; color: "yellow" }
            GradientStop { position: 1.0; color: "green" }
        }
        Gradient {
            id:second
            GradientStop { position: 0.0; color: "red" }
        }

        MouseArea{
            anchors.fill:parent
            onClicked: {
                parent.gradient=second
                numAni.running = true;
            }
        }

        NumberAnimation{
            target:smallRect
            id:numAni
            properties: "x";
            to: 100;
            duration: 1000

            onRunningChanged:{
                if (!numAni.running) {
                    console.log("numAni Animation completed");
                } else {
                    console.log("numAni Animation started");
                }
            }
        }

        Rectangle{
            id:smallRect
            width:10;
            height:10;
        }
    }

Saturday, March 5, 2011

Flipping (Rotating) view animation in QML

While I was creating view for my QML application, I thought to add some cool animation effect on view change. So I decided to add view flipping effect on view change event.

I am here sharing simple version of my view flipping code. First in my main view I created simple toolbar with two button, on clicking button it activate or flip according view.

I am skipping toolbar code here, go to end of post to find code for creating toolbar. So to achieve view flipping effect we can use Flipable QML element. We can add front and back to this element and can add animation on Rotation. Folloging code shows how it can be done.
Flipable {
        id: myFlip
        x:0
        y:50
        width: 800
        height: 430

        function showFront() {
            rot.angle=0;
        }

        function showBack() {
            rot.angle=180;
        }

        transform: Rotation {
            id: rot
            origin.x: 400;
            origin.y:100;
            axis.x:0; axis.y:1; axis.z:0
            angle:0

            Behavior on angle { PropertyAnimation{} }
        }

        front: Item {
            Rectangle {
                width: 800
                height: 430
                color:"green"
            }

            Text {
                x: 0
                y:200
                text: "My super cool green view"
            }
        }

        back: Item {

            Rectangle {
                width: 800
                height: 430
                color:"red"
            }

            Text {
                x: 0
                y:200
                text: "My super cool red view"
            }
        }
    }

In above code, I have added two Item element which act as my view and attached it to front side and back side. Then I have added Rotation transformation and added ProperyAnimation when angle changes. Also added two function which shows front or back side by invoking it.

Above code works fine to flip view, but if you have some content in back view then you will see content mirrored. See below snap.


To view proper content we need to remove rotation on content. To do this we can add another Rotation transformation on back view to zero effect of earlier rotation. So our back view code will look like below.
back: Item {

            transform:Rotation {
                origin.x: 400;
                origin.y:100;
                axis.x:0; axis.y:1; axis.z:0
                angle:180
            }

            Rectangle {
                 width: 800
                 height: 430
                 color:"red"
            }

            Text {
                x: 0
                y:200
                text: "My super cool red view"
            }
        }
Now view will look fine, like shown in below pic.


So this was all required to achieve view flipping effect, Following is demo of my sample app.



If you are interested in my simple toolbar then following is code for my toolbar.
    Rectangle {
        id: toolbar
        width:200
        height: 50
        color:"black"

        Image {
            x:10
            y:5
            id: btn1
            source: "btn1.png"

            MouseArea{
                anchors.fill : parent
                onClicked: {
                    console.log("Btn 1 clicked");
                    myFlip.showFront();
                }
            }
        }

        Image {
            x: 60
            y:5
            id: btn2
            source: "btn2.png"
            MouseArea{
                anchors.fill : parent
                onClicked: {
                    console.log("Btn 2 clicked");
                    myFlip.showBack();
                }
            }
        }
    }

Sunday, January 30, 2011

Simple animation with iPhone SDK

Recently I was trying port my application on iPhone and want to convert my Qt Animation code to iPhone SDK.

I achieved animation using core animation toolkit provided by iPhone SDK. In iPhone animation is performed using UIView object. You can animate changes to view property like frame, bounds, alpha, center, etc....

On iOS 4 and later animation can be done using block objects but if you want to run your code on iOS 3.2 or earlier than you have to use older begin/commit method.

I used begin/commit method to perform animation in my code.

Following snippet shows sample code that I used to animate a button's center to certain location.

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];

// Make the animatable changes.
btn1.center = CGPointMake(150, btn1.center.y);

// Commit the changes and perform the animation.
[UIView commitAnimations];

Same code can also be written using new block object, like following.

[UIView animateWithDuration:1.0 animations:^{
btn1.center = CGPointMake(150, btn1.center.y);
}];

Tuesday, January 25, 2011

Intel App Up developer program MeeGo Contest


Sometime ago intel launched App Up developer program and as part of that they launched MeeGo Contest and invited article for meego or Qt development on various topics.

I also submitted my article "Animating object along with curve in Qt using QPainterPath" for this competition for code sample topic and to my surprise it was selected as one of finalist. Check other entries here.

Now that winners are announced for each category and I am not one of them but still I will getting price for being one of finalist. Check winner list here.

Monday, November 29, 2010

Animating object along with curve in Qt using QPainterPath

Recently I was playing with Qt and found QPainterPath class. While reading documentation, I thought how can I use QPainterPath class and I created following prototype application in result.

QPainterPath can contain many different kind of shapes and we can draw all those shape using drawPath API of QPainter. But I used it to animate an object on curve path instead of just drawing, QPainterPath has some intresting API using which curve animation is quite easy.

In my sample app, I want to animate dot on curve as shown in below pic.


To achieve this, I first created a curved QPainterPath like following,
QPainterPath path;
path.moveTo(100,100);
path.quadTo(100,600,400,400);
Above code will draw curve as shown in above pic.

Now I created a timer and on timeout event, I am updating progress of dot on curve painter path. Like below.
void timeout()
{
    progress += 0.01;
    if( progress > 1 ) {
        progress  = 0;
    }
    update();
}
Now that, I have progress of dot on curve path at certain point in terms of percentage.QPainterPath has API pointAtPercent(), that can be used to get point on curve path at progress value and can draw Dot object at that point like below.
void Testwidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPath( path );

    painter.setBrush(Qt::SolidPattern);
    painter.drawEllipse(path.pointAtPercent(progress),20,20);
}
Output of above code will look like following.


If you don't like creating animation using QTimer and wants same output using Qt's animation framework then following code shows how that can be done.

In following code, I have created a custom widget named DotWidget and I am animating it on curve path using QPropertyAnimation.

Following code creates a painter path and a widget then applies QPropertyAnimation on it.
createPath();
DotWidget* dotWidget = new DotWidget(this);

QPropertyAnimation* animation = new QPropertyAnimation(dotWidget,
                               "geometry",this);
animation->setDuration(20000);
animation->setEasingCurve(QEasingCurve::Linear);
animation->setLoopCount(-1); //loop forever

//setting value for animation on different position using QPainterPath
for( double i = 0 ; i < 1; i = i+0.1) {
    animation->setKeyValueAt(i,
               QRect(path.pointAtPercent(i).toPoint(),QSize(30,30)));
}
animation->start(); 
Following is code for DotWidget custom widget class. Its very simple widget that draws circle.
#include 
#include 
class DotWidget : public QWidget
{
    Q_OBJECT
public:
    explicit DotWidget(QWidget *parent = 0)
        :QWidget(parent)
    {}

    void paintEvent(QPaintEvent *)
    {
        QPainter painter(this);
        painter.setBrush(Qt::SolidPattern);
        painter.drawEllipse(0,0,25,25);
    }
};
I have created custom widget just to show how it can be done with custom widget, but you can apply same animation of any widget. I have uploaded video that shows output with QPushButton at end of post.

Thats all,following is video for custom animation with timer.



Following is video for animation using QPropertyAnimation with QPushButton

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.

Saturday, April 24, 2010

Simple sprite animation using Qt

I was always wondering how character are animated in games so I thought to create simple animated character using Qt.

Technique is quite simple, you need to draw sequence of image with different character position.
To hold image of different character position I am using QList.

mLeftSprite.append( QPixmap(":left_1.png"));
mLeftSprite.append( QPixmap(":left_2.png"));
mLeftSprite.append( QPixmap(":left_3.png"));
mLeftSprite.append( QPixmap(":left_4.png"));
mLeftSprite.append( QPixmap(":left_5.png"));
mLeftSprite.append( QPixmap(":left_6.png"));  

To animate character I have used timer which timeout after every 100ms and I am displaying next caracter image when timer expire and also updating character position on screen at same time

mCurrentFrame = ++mCurrentFrame % 6;
mPos.setX( mPos.x() + mXDir * 10 ); 
  
And finally draw image on screen
 
painter->drawPixmap(mPos,(*mCurrentSprite)[mCurrentFrame]);

So end result is like following.



If you are instrested in looking at code than here is link to gitorious.