How to animate sprites

    This site uses cookies. By continuing to browse this site, you are agreeing to our Cookie Policy.

    • How to animate sprites

      In this short tutorial I want to show you how to play 2D animations with GFX. The first thing to say is that 2D animations can only be played with the Sprite GameElement. For this we need a sprite itself as well as an animation sheet which represents the different frames. I picked an CC0 animation sheet for this tutorial which you can find in the attachments. Thanks to the artist wich created this sheet (Character sprite + walk animation | OpenGameArt.org).

      C Source Code

      1. var sprite = new Sprite("sprite", new Vec3(0, 0), new Vec3(48, 48), this.AssetManager.GetTexture("ch003.png"));
      2. var animationBehavior = sprite.AddBehavior<AnimationBehavior>(new AnimationBehavior(4, 4, 50, this.AssetManager.GetTexture("ch003.png")));
      3. animationBehavior.AddAnimation(new Animation("WalkDown", 0, 0, 4));
      As you can see we are creating a sprite in the first line. It is important that you give it a texture. You can use the animation sheet or a dummy texture. In the second line we create the AnimationBehaviour and specify how many columns and rows it has, the frame time and the texture. Then we use AddAnimation to define an animation within this sprite. In our case it is the animation for the downswing.

      Source Code

      1. this.OnInit += (g, r) =>
      2. {
      3. animationBehavior.LoadAnimation("WalkDown");
      4. animationBehavior.Play();
      5. };
      In the OnInit event of our game we then load an animation and play it. The animations can also be loaded, changed and played during the game.
      Images
      • ch003.png

        5.65 kB, 128×128, viewed 12,029 times