使用 Flame 定位 SpriteComponent

SpriteComponent positioning with Flame

UPDATE:我创建了一个更小的示例,可能更好地说明了这个问题中的问题:https://github.com/flame-engine/flame/issues/200

短版:

我在 (50, 50), (50, 100), (100, 50), (100, 100).

位置实例化 SpriteComponents

但是,渲染后它们看起来像这样:

是什么产生了这种奇怪的偏差?如何正确渲染 SpriteComponents?

更长的版本(带代码): 我想通过实现 bunnymark 之类的东西来测试 flame 的性能。 作为节省性能的第一次尝试,我正在加载一个 Sprite 并使用它来生成许多 SpriteComponents.

SpriteComponent 包裹在 Bunny class 中。现在它什么都不做,最终它会处理运动:

import 'dart:ui';

import 'package:flame/components/component.dart';
import 'package:flame/sprite.dart';

class Bunny {
  SpriteComponent bunny;

  Bunny(Sprite bunnySprite, double x, double y, double w, double h)
      : this.bunny =
            SpriteComponent.fromSprite(w, h, bunnySprite) {
    bunny.x = x;
    bunny.y = y;
  }

  void render(Canvas c) {
    bunny.render(c);
  }

  void update(double t) {}
}

兔子在我的游戏中被实例化了class:

import 'dart:ui';

import 'package:bunnymark/components/bunny.dart';
import 'package:flame/flame.dart';
import 'package:flame/game.dart';
import 'package:flame/sprite.dart';
import 'package:flutter/cupertino.dart';

class BunnyMark extends Game {
  Size screenSize;
  List<Bunny> bunnies;
  Sprite bunnySprite;

  BunnyMark() {
    initialize();
  }

  void initialize() async {
    resize(await Flame.util.initialDimensions());

    bunnies = List<Bunny>();
    bunnySprite = Sprite('rabbitv3_tron.png');

    bunnies.add(Bunny(bunnySprite, 50, 50, 30, 30));
    bunnies.add(Bunny(bunnySprite, 50, 100, 30, 30));
    bunnies.add(Bunny(bunnySprite, 100, 100, 30, 30));
    bunnies.add(Bunny(bunnySprite, 100, 50, 30, 30));
  }

  void render(Canvas canvas) {
    Rect bgRect = Rect.fromLTWH(0, 0, screenSize.width, screenSize.height);
    Paint bgPaint = Paint();
    bgPaint.color = Color(0xff000000);
    canvas.drawRect(bgRect, bgPaint);

    bunnies.forEach((bunny) {
      bunny.render(canvas);
    });
  }

  void update(double t) {
    bunnies.forEach((bunny) => bunny.update(t));
  }

  void resize(Size size) {
    screenSize = size;
    super.resize(size);
  }
}

游戏开始于main.dart:

import 'package:bunnymark/bunnymark.dart';
import 'package:flame/util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  Util flameUtil = Util();
  await flameUtil.fullScreen();
  await flameUtil.setOrientation(DeviceOrientation.portraitUp);

  BunnyMark game = BunnyMark();
  runApp(game.widget);
}

由于您使用的是 Game 而不是 BaseGame(这会为您做到这一点),因此您有责任在 render 实施中每次重置 canvas精灵.

允许组件在 Canvas 上进行他们想要的任何修改,并且需要重置 BaseGame(或您的情况下的游戏)。

所以当你这样做时

bunnies.forEach((bunny) {
  bunny.render(canvas);
});

您可能想要执行以下操作:

bunnies.forEach((bunny) {
  canvas.save();
  bunny.render(canvas);
  canvas.restore();
});

或者,作为替代方案,看看 BaseGame class 可以为您解决很多问题 :)