如何在屏幕调整大小时重建游戏?

问题描述 投票:0回答:1

我正在尝试使用

flame
框架创建一个网格,其中单元格大小取决于屏幕宽度。这是实现此目的的当前代码:

import 'dart:async';
import 'dart:ui';

import 'package:flame/components.dart';
import 'package:flutter/material.dart';

import './my_game.dart';

class GameGrid extends Component with HasGameRef<MyGame> {
  final paint = Paint()..color = Colors.white;

  @override
  FutureOr<void> onLoad() {
    super.onLoad();

    _paintGrid();
  }

  void _paintGrid() {
    // number of rows and cols
    const numRows = 7;
    const numCols = 5;

    // screen size
    final screenSize = gameRef.size;

    // cell spacing
    const cellSpacing = 5.0;

    // cell size
    final cellSize = (screenSize.x / numCols) - (cellSpacing * (numCols - 1));

    // calculating starting point of the grid
    final startingTopLeftOfGrid = Vector2(
      -(((cellSize * numCols) + (cellSpacing * (numCols - 1))) / 2),
      -(((cellSize * numRows) + (cellSpacing * (numRows - 1))) / 2),
    );

    for (int i = 0; i < numRows; i++) {
      for (int j = 0; j < numCols; j++) {
        final cell = Cell(
          position: Vector2(
            startingTopLeftOfGrid.x + (j * (cellSize + cellSpacing)),
            startingTopLeftOfGrid.y + (i * (cellSize + cellSpacing)),
          ),
          size: Vector2.all(cellSize),
        );

        add(cell);
      }
    }
  }
}

class Cell extends RectangleComponent {
  Cell({
    required super.position,
    required super.size,
    super.anchor,
    super.paint,
  });
}

现在我想要的是如果屏幕大小调整则调整网格大小。例如在桌面应用程序上,当用户调整游戏窗口大小时,我希望网格根据新的屏幕宽度进行渲染。我怎样才能做到这一点?谢谢你

flutter flame
1个回答
0
投票

最简单的选择是使用

CameraComponent.withFixedResolution
,它使用
FixedResolutionViewport
,因此游戏中的所有内容都将根据窗口大小放大/缩小。这样做的缺点是,当宽高比不匹配时,侧面会出现黑条。

只需将扩展

FlameGame
的类更改为:

class MyGame extend FlameGame {
  MyGame() : super(
    camera: CameraComponent.withFixedResolution(
      width: 800,
      height: 600,
    ),
  );
}

另一个选项是覆盖

onGameResize
并创建设置其中单元格的大小,所有组件都有
onGameResize
:

@override
void onGameResize(Vector2 size) {
  // Use `size` to set the sizes of your cells, I would 
  // to not re-create the components in here, since you then have to
  // remove all the cells that you created before.
}
© www.soinside.com 2019 - 2024. All rights reserved.