我是Flutter的一个biginner,我正在练习制作一个像Temple Run或Flight to Fight Game这样的游戏,移动玩家以避免或获得即将到来的东西(我为它命名了一个类星星。)我试着做一个代码,当一个玩家和一个星星碰撞时,一个星星消失,分数变高。我的问题是,当一个玩家和一个星星碰撞时,星星不会消失,但只是通过播放器。你能检查一下这个问题吗?谢谢。
import 'package:flutter/material.dart';
import 'package:flame/game.dart';
import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'dart:math';
import 'package:flame/collisions.dart';
class GamePlay extends StatelessWidget {
const GamePlay ({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: GameWidget(
game: RacingGame(),
),
);
}
}
class Player extends RectangleComponent with CollisionCallbacks {
static const playerSize = 96.0;
Player({required position})
: super(
position: position,
size: Vector2.all(playerSize),
anchor: Anchor.bottomCenter,
);
@override
Future<void> onLoad() async {
super.onLoad();
paint.color = Colors.blue;
add(RectangleHitbox());
}
}
class RacingGame extends FlameGame with TapCallbacks {
late Player player;
double nextSpawnSeconds = 0.0;
@override
Future<void> onLoad() async {
player = Player(
position: Vector2(size.x * 0.25, size.y - 20),
);
add(player);
}
@override
void onTapDown(TapDownEvent event) {
super.onTapDown(event);
if (!event.handled) {
final touchPoint = event.canvasPosition;
if (touchPoint.x > size.x / 2) {
player.position = Vector2(size.x * 0.75, size.y - 20);
} else {
player.position = Vector2(size.x * 0.25, size.y - 20);
}
}
}
@override
void update(dt) {
super.update(dt);
nextSpawnSeconds -= dt;
if (nextSpawnSeconds < 0) {
add(Star(Vector2(size.x * (Random().nextInt(10) > 5 ? 0.75 : 0.25), 0)));
nextSpawnSeconds = 0.3 + Random().nextDouble() * 2;
}
}
}
class Star extends RectangleComponent with HasGameRef, CollisionCallbacks {
static const starSize = 64.0;
Star(position)
: super(
position: position,
size: Vector2.all(starSize),
anchor: Anchor.bottomCenter,
);
@override
Future<void> onLoad() async {
super.onLoad();
paint.color = Colors.yellow;
add(RectangleHitbox());
}
@override
void update(double dt) {
super.update(dt);
position.y = position.y + 5;
if ( position.y - size.y > gameRef.size.y ) {
removeFromParent();
}
}
@override
bool onComponentTypeCheck(PositionComponent other) {
if (other is Star) {
return false;
} else {
return super.onComponentTypeCheck(other);
}
}
@override
void onCollisionStart(
Set<Vector2> intersectionPoints,
PositionComponent other,
) {
if (other is Player) {
removeFromParent();
} else {
super.onCollisionStart(intersectionPoints, other);
}
}
}
字符串
1条答案
按热度按时间u3r8eeie1#
我解决了这个问题,对于任何遇到类似问题的人:我在类RacingGame的定义中添加了
HasCollisionDetection
。字符串