2

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

简洁版本:

SpriteComponents在位置实例化(50, 50), (50, 100), (100, 50), (100, 100).

但是,渲染后它们看起来像这样: 在此处输入图像描述

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

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

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

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) {}
}

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

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);
}
4

1 回答 1

3

由于您正在使用Game而不是BaseGame(这将为您执行此操作),因此您有责任在您的render实现中重置每个精灵的画布。

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

所以当你这样做时

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

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

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

或者,作为替代方案,看看BaseGame可以为您解决很多这些问题的课程:)

于 2020-01-12T18:15:49.000 回答