javascriptcraftyjs

Change sprite frame in Craftyjs


How do I manually set the sprite from frame 0 to frame 1?

//Load assets
Crafty.sprite("assets/img/q.png", {
qd1 : [ 0, 0, 17, 16 ],
qd2 : [ 0, 17, 17, 16 ]
});

var a=Crafty.e("2D, Canvas, SpriteAnimation, qd1").attr({x : 355, y : 225});

Solution

  • You change the sprite used from the spritesheet via Sprite.sprite().
    So in your case, to change the 1st sprite to the 2nd sprite in the second frame:

    Crafty.e("2D, Canvas, qd1")
          .attr({x : 355, y : 225})
          .one("EnterFrame", function() {
              this.sprite(0, 17, 17, 16);
          });
    

    Following is a snippet that demonstrates a constantly changing sprite. Notice the alternative notation for Crafty.sprite is used, which frees your mind to think in terms of tile coordinates, rather than pixel coordinates.

    Crafty.init();
    Crafty.background('white');
    
    // define spritesheet, each tile spans 60x60 px, 9 sprites in one row
    Crafty.sprite(60, "https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/images/spritesheet-2x.png", {
      first_sprite : [ 0, 0 ]
    });
    
    Crafty.e("2D, Canvas, first_sprite")
          .attr({x : 0, y : 0, idx : 0})
          .bind("EnterFrame", function(frameData) {
              if (frameData.frame % 100 === 0) // trigger roughly every 2 seconds
                this.sprite(++this.idx % 9, 0); // cycle through the 9 available sprites
          });
    <html>
    
    <head>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/crafty/0.6.3/crafty-min.js"></script>
    </head>
    
    <body>
    </body>
    
    </html>