Flutter Flame 熟悉使用 之 精灵动画

1,388 阅读2分钟

游戏开发中,除了最常见的图片,还有就是有动画的精灵了。Flame提供了非常简单好用的加载图片精灵的方法。 通过把一种精灵或者几种精灵同时放到一张图片中,可以减少图片数量的加载。

应用启动方法代码:

import 'package:flame/components/animation_component.dart';
import 'package:flame/flame.dart';
import 'package:flame/game.dart';
import 'package:flame/spritesheet.dart';
import 'package:flutter/widgets.dart';
import 'package:flame/animation.dart' as flame_animation;

void main() async{
    WidgetsFlutterBinding.ensureInitialized();
    Size size = await Flame.util.initialDimensions();
    runApp(FrogGame(size).widget);
}

提示:图片放在assets/images目录,需要添加到pubspec.yaml文件中。

主游戏界面: FrogGame继承于BaseGame,只需要使用BaseGame的add(Component c)就可以将各种Component加载到游戏中,并且会自动更新updaterender了。

class FrogGame extends BaseGame {
    String frogImageName = 'frog_run.png';
    
    FrogGame(Size screenSize) {
        size = screenSize;
        addFrog1();
        addFrog2();
        addFrog3();
    }
}
  • 加载方法1:Flame的Animation类,然后使用AnimationComponent加载即可,简单明了但是繁杂一点:

void addFrog1() {
    final animation = flame_animation.Animation.sequenced(frogImageName,12,
    amountPerRow: 12,
    textureWidth: 32,
    textureHeight: 32,
    );
    final animationComponent = AnimationComponent(100,100,animation);
    animationComponent.x = size.width / 2 -animationComponent.width/2;
    animationComponent.y = 50;
    add(animationComponent);
}

sequenced方法中,第一个12表示amount,就是精灵的总数量,amountPerRow表示一行的精灵数量,textureWidth和textureHeight表示单张精灵的宽度和高度。比如上述图片frog_run.png的像素宽高为 384*32,一行总共12个精灵,所以对应上述的数值。

AnimationComponent构造函数参数分别表示显示在屏幕上的宽高以及精灵动画,然后设置在屏幕的位置x/y。最后add(animationComponent)即可。

  • 加载方法2:简化方法1,直接使用AnimationComponent的sequenced方法,可以帮我们省略手动加载animation。

void addFrog2() {
    final animationComponent = AnimationComponent.sequenced(150, 150, frogImageName, 12, amountPerRow: 12, textureWidth: 32, textureHeight: 32);
    
    animationComponent.x = size.width / 2 - animationComponent.width / 2;
    animation.y = 150;
    add(animationComponent);
}
  • 加载方法3:使用SpriteSheet,可以将不同的精灵放在同一张图片中进行加载,减少项目中图片的数量,所用图片为

void addFrog3() {
    final spriteSheet = SpriteSheet(
        imageName: 'spritesheet.png',
        textureWidth: 16,
        textureHeight: 18,
        columns: 11,
        rows: 2);
    final animation = spriteSheet.createAnimation(0,stepTime: 0.1,to: 8);
    final animationComponent = AnimationComponent(80, 80, animation);
    animationComponent.x = size.width / 2 - 100;
    animationComponent.y = 300;
    add(animationComponent);

    final animation2 = spriteSheet.createAnimation(1,stepTime: 0.1,to: 8);
    final animationComponent2 = AnimationComponent(80, 80, animation2);
    animationComponent2.x = size.width / 2;
    animationComponent2.y = 300;
    add(animationComponent2);
}

结果如下图所示:

Flame简单加载精灵动画就是这样,谢谢观看。