我正在使用Flutter and flame (0.29.3)来构建一个简单的手机游戏。我正在尝试检测PositionComponent/SpriteComponent上的点击。然而,我没有做到这一点。参考/教程正在使用addGestureRecognizer,但它已被弃用。
我定义我的PositionComponent如下;
class Enemy extends PositionComponent with Tapable {
Rect enemyRect;
Enemy(double x, double y) {
enemyRect = Rect.fromLTWH(x, y, 50, 50);
}
@override
void render(Canvas c) {
Color color = Color(0XFFFF0000);
Paint enemyColor = Paint()..color = color;
c.drawRect(enemyRect, enemyColor);
}
void update(double t) {}
@override
void onTapUp(TapUpDetails details) {
print("tap up");
}
@override
void onTapDown(TapDownDetails details) {
print("tap down");
}
@override
void onTapCancel() {
print("tap cancel");
}
}然后,我把PositionComponent加入到我的游戏中。
class GameController extends BaseGame with HasTapableComponents {
Size screenSize;
double tileSize;
Player player;
Enemy enemy;
TapableComponent a;
GameController() {
initialize();
}
void initialize() async {
resize(await Flame.util.initialDimensions());
add(enemy = Enemy(200, 200));
}
@override
void render(Canvas c) {
Rect background = Rect.fromLTWH(0, 0, screenSize.width, screenSize.height);
Paint backgroundPaint = Paint()..color = Color(0xFFFAFAFA);
enemy.render(c);
}
@override
void update(double t) {}
@override
void resize(Size size) {
screenSize = size;
tileSize = screenSize.width / 10;
}
}但是,它不工作,我是不是遗漏了什么?
发布于 2021-03-14 22:20:10
我认为你的示例代码是v1代码和0.29.3的混合,如果你尝试使用Flame:1.0.0-rc8的最新候选版本,那么下面的代码应该可以工作:
class TapableSquare extends PositionComponent with Tapable {
static final Paint _white = Paint()..color = const Color(0xFFFFFFFF);
static final Paint _grey = Paint()..color = const Color(0xFFA5A5A5);
TapableSquare({Vector2 position})
: super(
position: position ?? Vector2.all(100),
size: Vector2.all(100),
);
@override
void render(Canvas canvas) {
super.render(canvas);
canvas.drawRect(size.toRect());
}
@override
bool onTapUp(TapUpDetails details) {...}
@override
bool onTapDown(TapDownDetails details) {...}
@override
bool onTapCancel() {...}
}
class TapablesGame extends BaseGame with HasTapableComponents {
@override
Future<void> onLoad() async {
add(TapableSquare());
}
}从这个example中提取。
编辑:为了让它在0.29.3上工作,你应该在你的Enemy类中设置position和size,而不是构建你自己的rect,Tapable不能知道那个rect。
https://stackoverflow.com/questions/66622684
复制相似问题