这是我第一次尝试使用Flame引擎Flutter制作游戏。但是,我遇到了相机问题,即使我将其设置为跟随,它也不会移动。我尝试将相机跟随代码移至更新函数,但它引发错误。
此外,我在官方 Flame 文档中找不到更多关于如何实现此功能的文档。
这是我的主要游戏代码。如有需要,请随时询问代码的其他部分。
import 'dart:async';
import 'dart:math';
import 'package:flame/events.dart';
import 'package:flame/flame.dart';
import 'package:flame/game.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:whirlybird/components/obstacle.dart';
import 'package:whirlybird/components/player.dart';
class GameScreen extends StatelessWidget {
const GameScreen({super.key});
@override
Widget build(BuildContext context) {
return GameWidget(
game: MainGame(),
);
}
}
class MainGame extends FlameGame with HorizontalDragDetector, HasCollisionDetection, TapDetector {
@override
Color backgroundColor() => Colors.white;
double birdX = 50;
double birdY = 500;
double birdSpeed = 0;
late double touchDownX;
late double screenWidth;
late double screenHeight;
late final Obstacle obstacle;
late final Player player;
@override
bool get debugMode => kDebugMode;
@override
void onRemove() {
Flame.images.clearCache();
Flame.assets.clearCache();
}
@override
FutureOr<void> onLoad() async {
// Load assets
screenWidth = size[0];
screenHeight = size[1];
final random = Random();
for (int i = 0; i < 10; i++) {
final x = random.nextDouble() * (size[0] - 10) + 10;
final y = random.nextDouble() * (size[1] - 10) + 10;
add(Obstacle(positionVector: Vector2(x, y)));
}
player = Player(positionVector: Vector2(birdX, birdY), collisionCallback: flap);
add(player);
player.position = Vector2(birdX, birdY); // Jump
camera.follow(player);
return super.onLoad();
}
void flap() {
birdSpeed = -5;
}
@override
void onHorizontalDragDown(DragDownInfo info) {
touchDownX = info.raw.globalPosition.dx;
}
@override
void onHorizontalDragUpdate(DragUpdateInfo info) {
double touchX = info.raw.globalPosition.dx;
double deltaX = touchX - touchDownX;
birdX += deltaX;
touchDownX = touchX;
}
@override
void update(double dt) {
birdY += birdSpeed;
birdSpeed += 0.1;
player.position = Vector2(birdX, birdY);
super.update(dt);
}
}
任何帮助将不胜感激!谢谢!
您使用的是哪个版本的 Flame?
如果是最新的,那么您必须将组件添加到世界对象而不是主游戏中。因此,不要使用
add(player);
,而是使用 world.add(player)
还要确保 Player 组件扩展了 PositionComponent 或具有使跟随机制正常工作的实现!