2 - Moving a sprite

  • Once you have created a TIGL View and loaded a sprite you can move it. The below code explain that in detail.

    # myView.xml
    1
    2
    3
    4
    5
    <Alloy>
      <Window>
        <TIGLView module="fr.dzzd.tigl" onInit="init" onResize="resize" onLoop="loop"/>
      </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
    43
    44
    45
    var spriteUid;
    var posX;
    var direction;
    var width;
    var height;
    function init()
    {
       /*
        * For Alloy project, at runtime "assets" folder become "Resources" folder
        */
        spriteUid = this.addSprite({url: "Resources/sprite.png", x: 0, y: 50});
        this.setEntityPivotById(spriteUid, 128, 160);
        posX = 128;
        direction=-1;
    }
    
    
    /*
     * Resize must be declared as an attribute of the Alloy tag TIGLView (eg: onResize="resize")
     */ 
    function resize(e)
    {
        width = e.width;
        height = e.height;
    }
    
    /*
     * Loop must be declared as an attribute of the Alloy tag TIGLView (eg: onLoop="loop")
     */ 
    function loop()
    {
        this.setEntityPositionById(spriteUid, posX, height * 0.5);
        posX+=direction;
        if(posX<128)
        {
            direction = 1;
            this.setEntityScaleById(spriteUid, -1, 1);
        }
        if(posX>width - 128)
        {
            direction = -1;
            this.setEntityScaleById(spriteUid, 1, 1);
        }
        
    }