Showing posts with label sprite sheet. Show all posts
Showing posts with label sprite sheet. Show all posts

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.

 

Sunday, October 20, 2013

Beginning 2D sprite animation with Unity3D

Now that Unity is free and you can develop app for Windows phone, BB10, Android and iOS using it. I thought to give it a try.

To learn it, I started with creating simple 2D game, in which I need to switch images on object when someone touches it. It too some time to get it done first time, but finally now I know how it can be done.

So let's get started.

First we need to setup Main camera.

- I seen some videos and in one of video, author suggested to set camera at x=0,y-0, z = -10
and rotation to x=0, y=180, z=0.  I decided to use the same.

- Set camera size as 1 as its easier to deal with

- Set projection to Orthographic for 2D games.

Setup light for 2D game

We dont need to use lighting for 2D game, so we will light up whole scene by following.

Edit-> Render setting ->Ambient Light



Change Ambient light to White, It should light up whole scene

Create a cube to represent 2D object

Now we should add some object to scene.

Actually I want to render 2D image on scene, but that's not possible so we will add some 3D object and apply material over it (which is our image). And render that object to represent our image.

To do that we can add cube to scene, with proper size, Ideally we just need a plane which only one face to represent image, as that will same memory, but to learn how it works, cube will do.

Add cube to scene by Create in Hierarchy and then cube.


set position as x = 0, y = 0, z = 10

You should see a Cube in your view now.

Import image as asset

Now drag image which we need to draw to asset window,
If you want to draw animation than Image needs to be sprite sheet, I created one myself with all images i needed to be displayed.

Create material with image and apply on the Cube

We can not add image diractly to Cube, we need to create material first.
To create material,

 Project window, create ->material


Now drag image over material's texture window.



Now you can apply this material to cube, by dragging material and dropping it on cube.



Now you can see the image, but you see whole sprite sheet.  We don't want that, we need to show only one portion of sprite sheet.



Let's click material again and you will see it has tiling and offset property.

So our sprite sheet has two sprite, thus tiling will be 0.5. Let's set tiling to 0.5. Now we see proper image on cube.



If you play with offset, you can see by manipulating it we can show different sprite on cube.

By setting offset to 0.5 you can show different image on cube. We will be using this property when we add support for event, on which we will show different image.



Its showing proper image but its also showing white background, but my image is transparent. We can add transparency by selecting proper Shader.

Click material, from Shader select -> Transparent ->cutout->Diffuse



You can play with Alpha cutoff value to adjust transparency. Now it should look like below.



Handle touch event so we can animate image on touch

Now we have our 2D object, we wan to add event on it. For that we need to add script to it.

Click on object -> from Inspector window -> select Add Component -> New Script

Name it and select scripting language of your choice, I selecte c# as scripting language.

Open script, and add following code in Update method.

 void Update () {  
  if( Input.anyKey ){
   gameObject.renderer.material.mainTextureOffset = new Vector2(0.5f,0); 
  } else {
   gameObject.renderer.material.mainTextureOffset = new Vector2(0.0f,0);
  }
 }

This script will check if any key is pressed. If pressed we are setting material offset to 0.5 else 0. To display different part of sprite sheet.

OK, We are done now. Here is how it works.


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.

Thursday, November 17, 2011

Virtual Joystick with QML

Recently out of curiosity I tried to created virtual joystick, which nowadayx s used quite frequently touch based games.

Well my implementation still required some improvement to provide real feel of joystick but its still quite useful. Here is output.

To test my joystick, I also created a sprite which moves in almost all direction.

Here is my QML code for joystick. I basically used two circle and checking inner circle position with outer circle and deciding direction. I am not describing code, but tried to put necessary comment in code.
import QtQuick 1.0

Item {
    id:joyStick;
    property int offset:30;

    signal dirChanged(string direction);
    signal pressed();
    signal released();

    Rectangle {
        id:totalArea
        color:"gray"
        radius: parent.width/2
        opacity: 0.5
        width:parent.width;height:parent.height
    }

    Rectangle{
        id:stick
        width:totalArea.width/2; height: width
        radius: width/2
        x: totalArea.width/2 - radius;
        y: totalArea.height/2 - radius;        
        color:"black"
    }

    MouseArea{
        id:mouseArea
        anchors.fill: parent

        onPressed: {
            joyStick.pressed();
        }

        onMousePositionChanged: {            
         //(x-center_x)^2 + (y - center_y)^2 < radius^2
         //if stick need to remain inside larger circle
         //var rad = (totalArea.radius - stick.radius);
         //if stick can go outside larger circle
         var rad = totalArea.radius;
         rad =  rad * rad;

         // calculate distance in x direction
         var xDist = mouseX - (totalArea.x + totalArea.radius);
         xDist = xDist * xDist;

         // calculate distance in y direction
         var yDist = mouseY - (totalArea.y + totalArea.radius);
         yDist = yDist * yDist;

         //total distance for inner circle
         var dist = xDist + yDist;            

         //if distance if less then radius then inner circle is inside larger circle
         if( rad < dist) {
             return;
         }

         //center of larger circle
         var oldX = stick.x; var oldY = stick.y;
         stick.x = mouseX - stick.radius;
         stick.y = mouseY - stick.radius;

         //using L R U D LU RU LD RD for describe direction
         var dir="";

         //check if Right or left direction, 
         //by checking if inner circle's y is near center of larger circle
         if( stick.y >= totalArea.radius - stick.radius - joyStick.offset 
 && stick.y+stick.height <= totalArea.radius + stick.radius + joyStick.offset) {
             if( stick.x + stick.radius > totalArea.x + totalArea.radius) {
                 dir = "R";
             } else if( stick.x < totalArea.x + totalArea.radius) {
                 dir = "L";
             }
         }
         //check if Up or Down direction, 
         //by checking if inner circle's x is near center of larger circle
         else if( stick.x >= totalArea.radius - stick.radius - joyStick.offset 
 && stick.x + stick.width <= totalArea.radius + stick.radius + joyStick.offset) {
            if( stick.y + stick.radius > totalArea.y + totalArea.radius) {
                 dir = "D";
            } else if( stick.y < totalArea.y + totalArea.radius) {
                 dir = "U";
            }
         }
         //check if Up Left or Up Right direction,
         //by checking if inner circle is near one of top corner of larger circle
         else if( stick.y < totalArea.radius - stick.radius ) {
            if( stick.x + stick.radius > totalArea.x + totalArea.radius) {
                dir = "R";
            } else if( stick.x < totalArea.x + totalArea.radius) {
                dir = "L";
            }
            dir = dir +"U";
         }
         //check if Down Left or Down Right direction,
         //by checking if inner circle is near one of bottom corner of larger circle
         else if ( stick.y + stick.radius >= totalArea.radius + stick.radius ) {
            if( stick.x + stick.radius > totalArea.x + totalArea.radius) {
               dir = "R";
            } else if( stick.x < totalArea.x + totalArea.radius) {
               dir = "L";
            }
            dir = dir +"D";
         }

         joyStick.dirChanged(dir);
        }

        onReleased: {
            //snap to center
            stick.x = totalArea.width /2 - stick.radius;
            stick.y = totalArea.height/2 - stick.radius;

            joyStick.released();
        }
    }
}

Follwing my code for sprite used in above video.
import QtQuick 1.0

Item {
    id:sprite
    width: 50; height: 50
    clip:true
    property alias running: timer.running;
    property int frameCount: 5
    property int frame:0
    property int row:0

    property int xDir:0;
    property int yDir:0;

    Image{
        id:image
        source:"man.png"
        x:-sprite.width * sprite.frame;
        y:-sprite.height * sprite.row;
    }

    function changeDirection(direction) {
        if( direction === "L") {
            sprite.row=6;
            sprite.xDir = -1;
            sprite.yDir = 0;
        } else if( direction === "R") {
            sprite.row=2;
            sprite.xDir = 1;
            sprite.yDir = 0;
        } else if( direction === "U") {
            sprite.row=4;
            sprite.xDir = 0;
            sprite.yDir = -1;
        } else if( direction === "D") {
            sprite.row=0;
            sprite.xDir = 0;
            sprite.yDir = 1;
        } else if( direction === "RU") {
            sprite.row = 3;
            sprite.xDir = 1;
            sprite.yDir = -1;
        } else if( direction === "LU") {
            sprite.row = 5;
            sprite.xDir = -1;
            sprite.yDir = -1;
        } else if( direction === "RD") {
            sprite.row = 1;
            sprite.xDir = 1;
            sprite.yDir = 1;
        } else if( direction === "LD") {
            sprite.row = 7;
            sprite.xDir = -1;
            sprite.yDir = 1;
        }
    }

    function nextFrame() {
        sprite.frame = ++sprite.frame  % sprite.frameCount
        sprite.x = sprite.x + 5* sprite.xDir;
        sprite.y = sprite.y + 5* sprite.yDir;
    }

    Timer {
       id:timer
       interval: 150; running: false; repeat: true
       onTriggered: {
           nextFrame();
       }
    }
}
Finally, main qml file which include both joystick and sprite.
import QtQuick 1.0

Image {
    width: 854 ;  height:480    
    source:"grass.jpg"
    fillMode: Image.Tile

    Sprite{
        id:man
        x:parent.width/2 ; y: parent.height/2;
    }

    Connections {
        target: joyStick
        onDirChanged:{
            man.changeDirection(direction)
        }

        onPressed:{
            man.running=true;
        }

        onReleased:{
            man.running=false;
        }
    }

    Joystick{
        id:joyStick
        anchors.bottom: parent.bottom
        anchors.left: parent.left
        anchors.bottomMargin: 10
        anchors.leftMargin: 10
        width:150;height:150
    }
}


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.

Saturday, November 13, 2010

Sprite animation with SVG sprite sheet in Qt Graphics View

Recently I started to port my game to Symbian platform,
In my previous post I showed how to make graphics work with different resolution.But if you are using images in application, you need to use SVG image to make sure that images looks good in all resoltion.

When I started to replace my game images with SVG image, I need to make changes in my sprite class.With normal images I was drawing only certain portion of image from Sprite sheet like code in this post, but I could not make that thing work with SVG. Then to make my sprite class work I made following changes.

In following code, I am using SVG file which contain each frame with unique id and in code on next frame I am rendering SVG element with id for particular frame.

Code for animatedsvgitem.h
#ifndef ANIMATEDSVGITEM_H
#define ANIMATEDSVGITEM_H

#include <QGraphicsSvgItem>
#include <QTimer>

class AnimatedSvgItem : public QGraphicsSvgItem
{
    Q_OBJECT
public:
    AnimatedSvgItem();
    QRectF boundingRect() const;

private slots:
    void nextFrame();

private:
    QTimer *timer;
    QStringList frames;
    int currentFrame;
};
#endif // ANIMATEDSVGITEM_H

Code for animatedsvgitem.cpp
#include "animatedsvgitem.h"

AnimatedSvgItem::AnimatedSvgItem()
    :QGraphicsSvgItem( QString(":/egg.svg") )
{
    //svg element id of frame in svg file
    frames << "egg1" << "egg2" << "egg3" << "egg4" << "egg5" << "egg6" << "egg7" << "egg8";
    currentFrame = 0;
    this->setElementId( frames[currentFrame] );
    timer = new QTimer(this);
    QObject::connect(timer,SIGNAL(timeout()),this,SLOT(nextFrame()));
    timer->start(400);
}

QRectF AnimatedSvgItem::boundingRect() const
{
    return QRectF(0,0,20,20);
}

void AnimatedSvgItem::nextFrame()
{
    currentFrame = ++currentFrame % 8;
    this->setElementId( frames[currentFrame]);
    this->moveBy(5,0);
    update();
}
So this was all, Sprite sheet used for above code is like this but in SVG format.





Here video from sample code.

Thursday, October 21, 2010

Using QStateMachine with sprite animation

In 4.6 Qt introduced new State machine framework. Framework looks quite easy to use and extensible for complex use-case.
To explore Qt's State machine framework I thought to use it with sprite animation, as a complex sprite also holds many state and maintaining sprite state and transition from one state to another can become pain if not done properly.

So following is my sample code for prince sprite which use QStateMachine to maintain sprite's state and transition from one state to another. From somewhere in Internet I found sprite sheet for Prince of Persia, to make it easy for sample code I created another simple version of original sprite sheet.
PrinceSprite::PrinceSprite(QGraphicsItem * parent)
    :QGraphicsObject(parent)
{
    mSpriteImage = new QPixmap(":/prince.png");
    changeDir(this);

    //creating different state object , 
    //which are derived from QState and l
    //istening to timer's timeout signal 
    //and also modify frame according to animation
    StandingState* standing = new StandingState(this);
    RunningState* running = new RunningState(this);
    PrepareForAttack* prepareForAttack = 
                        new PrepareForAttack(this);
    Attack* attack = new Attack(this);
    InAttackMode* inAttackMode = new InAttackMode(this);

    //adding transition to state
    //goto running state from stating state at left click
    standing->addTransition(this,SIGNAL(leftClick()),running);
    running->addTransition(this,SIGNAL(leftClick()),standing);
    standing->addTransition(this,SIGNAL(rightClick())
                                    ,prepareForAttack);
    prepareForAttack->addTransition(prepareForAttack,
                        SIGNAL(exited()),inAttackMode);
    inAttackMode->addTransition(this,SIGNAL(leftClick()),attack);
    attack->addTransition(attack,SIGNAL(exited()),inAttackMode);
    inAttackMode->addTransition(this,
                     SIGNAL(rightClick()),standing);

    //adding all state to QStateMachine
    _stateMachine.addState(standing);
    _stateMachine.addState(running);
    _stateMachine.addState(prepareForAttack);
    _stateMachine.addState(attack);
    _stateMachine.addState(inAttackMode);

    //setting initial state and then starting state machine
    _stateMachine.setInitialState( standing);
    _stateMachine.start();
}

In above code I have create different state object for different sprite state, like for StandingState or Attack state.
This state classes are derived from QState class and listen to QTimer's timeout signal to change frame according to animation.

For example following code for Attack state.
#include <QState>

class Attack : public QState
{
    Q_OBJECT
public:
    Attack(PrinceSprite* prince);
    void onEntry ( QEvent * event );
    void onExit ( QEvent * event );

signals:
    void exited();

private slots:
    void nextFrame();
};

#include "attack.h"

Attack::Attack(PrinceSprite* prince)
    :QState()
{}

void Attack::nextFrame()
{    
    _prince->_x += 1;
    _prince->setX(_prince->x() + 7);
    if (_prince->_x >= 4 ) {
        emit exited();
    }
}

void Attack::onEntry ( QEvent * event )
{
    QObject::connect(_prince,SIGNAL(tick()),
                     this,SLOT(nextFrame()));
    _prince->_x = 0;
    _prince->_y = 2;
}

void Attack::onExit ( QEvent * event )
{
    QObject::disconnect(_prince,SIGNAL(tick()),
                        this,SLOT(nextFrame()));
}

So finally, I am not sure if this is correct approach to implement sprite or not, but using Qt's State machine framework is helping a lot to make it simpler.

Follwing is demo of my implementation.

Monday, August 16, 2010

Creating custom graphics item in Qt's graphics view

Now a days I started to learn Qt's Graphics view. Initially I was struggling with it but once I started programming with it I found that its quite easy and powerful. What I like most about it is, while creating custom item we can perform paint opration with items local coordinate and need not worry about scene coordinate.

While creating custom graphics item, Your class needs to be derived from QGraphicsItem or QGraphicsObject. If your object needs to use signal/slot than derive your class from QGraphicsObject else derive it from QGraphicsItem and override paint and boundingRect methods.

For test application I tried to create sprite with custom graphics item that shows rolling ball animation. Following is code for my custom graphics item.
#include <QGraphicsObject>
#include <QPixmap>

class BallGraphicsItem : public QGraphicsObject
{
    Q_OBJECT
public:

    BallGraphicsItem();
    ~BallGraphicsItem();

    void paint ( QPainter * painter, 
const QStyleOptionGraphicsItem * option, 
QWidget * widget = 0 );

    QRectF boundingRect() const;

public slots:
    void move();
    void nextFrame();
private:

    QPixmap mBallImage;    
    int mCurrentRow;
    int mCurrentColumn;    
};

#endif // BALLGRAPHICSITEM_H

#include "ballgraphicsitem.h"
#include <QPainter>
#include <math.h>
#include <QBitmap>


BallGraphicsItem::BallGraphicsItem()
    :QGraphicsObject( ),mBallImage(":sphere.bmp"),
mCurrentRow(0),mCurrentColumn(0)
{
    //masking image to make image transperent
    mBallImage.setMask( 
mBallImage.createMaskFromColor(QColor(255,0,255)));    
}

BallGraphicsItem::~BallGraphicsItem()
{}

QRectF BallGraphicsItem::boundingRect() const
{
    return QRectF(0,0,32,32);
}

void BallGraphicsItem::paint ( QPainter *painter, 
const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/ )
{
    painter->drawPixmap(0,0,mBallImage, 
mCurrentColumn* 32 ,mCurrentRow*32, 32,32);
}

void BallGraphicsItem::nextFrame()
{
    mCurrentColumn = ++mCurrentColumn % 8;
    if( mCurrentColumn == 0 ) {
        mCurrentRow = ++mCurrentRow %4;
    }
}

void BallGraphicsItem::move()
{    
    setPos( x() + 2, y());
    nextFrame();
}

And my main.cpp file looks like following.
#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QTimer>
#include "ballgraphicsitem.h"

int main( int argc, char* argv[] )
{
    QApplication app(argc,argv);

    QGraphicsScene scene( 0, 0, 840, 480 );
    QGraphicsView view(&scene);
    view.setRenderHint(QPainter::Antialiasing);
    view.show();

    BallGraphicsItem* ball = new BallGraphicsItem();
    ball->setPos(10,10);
    scene.addItem( ball );

    QTimer *timer = new QTimer(qApp);
    timer->start(1000/30);
    QObject::connect(timer,SIGNAL(timeout()),ball,SLOT(move()));

    return app.exec();
} 
For above code I am using following image, don't know from where I downloaded image.

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.