所以目前我正在尝试学习 Flame 框架来用 flutter 构建游戏。我的用例涉及创建一个网格并监听该网格上的点击。在网格内点击某个单元格后,我需要突出显示该单元格。像这样的事情可以在 flutter 中实现如下:
import 'package:equatable/equatable.dart';
import 'package:flame/game.dart';
import 'package:flutter/material.dart';
import './src/my_game.dart';
void main() {
// final game = MyGame();
// runApp(GameWidget(game: game));
runApp(Grid());
}
class Grid extends StatefulWidget {
const Grid({super.key});
@override
State<Grid> createState() => _GridState();
}
class Position extends Equatable {
final int rowIndex;
final int colIndex;
const Position(this.rowIndex, this.colIndex);
@override
List<Object?> get props => [rowIndex, colIndex];
}
class _GridState extends State<Grid> {
final List<Position> selectedPositions = [];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Grid'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: List.generate(8, (rowIndex) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(8, (colIndex) {
return GestureDetector(
onTap: () {
setState(() {
selectedPositions.add(Position(rowIndex, colIndex));
});
},
child: Container(
height: 20,
width: 20,
decoration: BoxDecoration(
border: Border.all(width: 1, color: Colors.black),
color: selectedPositions
.contains(Position(rowIndex, colIndex))
? Colors.red
: null,
),
),
);
}),
);
}),
),
),
);
}
}
但我不知道如何通过
render()
方法在 Flame 中获得相同的东西。有人可以指导我或者提供有关如何完成此操作的示例代码吗?非常感谢。
说实话,我真的无法尝试任何事情。我深入思考了如何做这样的事情,但无法弄清楚。我尝试检查其他资源,如 Youtube、文章等,但无法理解。
使用
RectangleComponent
创建一个 TapCallbacks
并使用例如嵌套 for 循环将它们放置在网格中。
类似这样的:
class MyTile extends RectangleComponent with TapCallbacks {
MyTile({required super.position}) : super(size: Vector2(tileWidth, tileHeight));
@override
void onTapDown(TapDownEvent event) {
...
}
}
...
for(var y = 0; y * tileHeight < size.y; y++) {
for(var x = 0; x * tileWidth < size.x; x++) {
add(
MyTile(
position: Vector2(x * tileWidth, y * tileHeight),
),
);
}
}