3 - Animating a sprite

  • You can do more than just moving a sprite, you can also animate it ! using sprite sheet.
  • Sprite sheet is a process that consist of having multiple appearances of a sprite in a single image, those can be changed programatical to animate the sprite.
  • Look at below image and source code to see how you can create and animate a sprite using a sprite sheet.

    spritesheet.png (source: https://www.codeandweb.com/)

    # myView.xml
    <
    1
    2
    3
    4
    5
    <Alloy>
      <Window>
        <TIGLView module="fr.dzzd.tigl" onInit="init" onResize="resize"/>
      </Window>
    </Alloy>
    


    # myView.js
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    var sprite1Uid;
    var sprite2Uid;
    var sprite3Uid;
    var sprite4Uid;
    var width;
    var height;
    
    /*
     * Init must be declared as an attribute of the Alloy tag TIGLView (eg: onInit="init")
     */
    function init()
    {
        /*
        * For Alloy project, at runtime "assets" folder become "Resources" folder
        */
        sprite1Uid = this.addSprite({url: "Resources/numbersBlue.png", x: 0, y: 0, width: 46, height: 46});
        sprite2Uid = this.addSprite({url: "Resources/numbersBlue.png", x: 46, y: 0, width: 46, height: 46});
        sprite3Uid = this.addSprite({url: "Resources/numbersBlue.png", x: 46*2, y: 0, width: 46, height: 46});
        sprite4Uid = this.addSprite({url: "Resources/spritesheet.png", x: 100, y: 50, width: 256, height: 256});
    
        /*
         * Play some animations with different parameters
         */
        this.playEntityAnimationById(sprite1Uid, {duration: 5000});
        this.playEntityAnimationById(sprite2Uid, {duration: 5000, start: 9, end: 0});
        this.playEntityAnimationById(sprite3Uid, {duration: 4000, pingpong: true, loop: 50});
        this.playEntityAnimationById(sprite4Uid, {duration: 500, loop: 0});
    }
    
    
    /*
     * Resize must be declared as an attribute of the Alloy tag TIGLView (eg: onResize="resize")
     */ 
    function resize(e)
    {
        width = e.width;
        height = e.height;
        /*
         * Center sprite 4
         */
        this.setEntityPositionById(sprite4Uid, width * 0.5 - 128, height * 0.5 - 160);
    }