如何在 Flutter 中使用 Flame 检测屏幕边界?
How to detect screen boundaries with Flame in Flutter?
我想在 Flame Flutter 中检测物体何时离开屏幕。我认为有两种方法可以通过 Collidable
mixin 或 Forge2D 来实现。如果可能的话,在两者中都解释一下。
火焰版本:火焰:1.0.0-releasecandidate.18
为此使用 Forge2D
太过分了(这也使很多其他事情复杂化)。但是你可以使用内置的碰撞检测系统,或者你可以在更新循环中检查它是否在屏幕内(这将是最有效的)。
通过使用碰撞检测系统,我们可以使用内置的 ScreenCollidable
,您可以这样做:
class ExampleGame extends FlameGame with HasCollidables {
...
@override
Future<void> onLoad() async {
await super.onLoad();
add(ScreenCollidable());
}
}
class YourComponent extends PositionComponent with HasHitboxes, Collidable {
@override
Future<void> onLoad() async {
await super.onLoad();
// Change this if you want the components to collide with each other
// and not only the screen.
collidableType = CollidableType.passive;
addHitbox(HitboxRectangle());
}
// Do note that this doesn't work if the component starts
// to go outside of the screen but then comes back.
@override
void onCollisionEnd(Collidable other) {
if (other is ScreenCollidable) {
removeFromParent();
}
}
}
并在 update
循环中计算它:
class YourComponent extends PositionComponent with HasGameRef {
@override
void update(double dt) {
final topLeft = absoluteTopLeftPosition;
final gameSize = gameRef.size;
if(topLeft.x > gameSize.x || topLeft.y > gameSize.y) {
removeFromParent();
return;
}
final bottomRight = absolutePositionOfAnchor(Anchor.bottomRight);
if(bottomRight.x < 0 || bottomRight.y < 0) {
removeFromParent();
return;
}
}
}
我还建议您在 Flame 1.0.0 发布时立即更新到它。 :)
我想在 Flame Flutter 中检测物体何时离开屏幕。我认为有两种方法可以通过 Collidable
mixin 或 Forge2D 来实现。如果可能的话,在两者中都解释一下。
火焰版本:火焰:1.0.0-releasecandidate.18
为此使用 Forge2D
太过分了(这也使很多其他事情复杂化)。但是你可以使用内置的碰撞检测系统,或者你可以在更新循环中检查它是否在屏幕内(这将是最有效的)。
通过使用碰撞检测系统,我们可以使用内置的 ScreenCollidable
,您可以这样做:
class ExampleGame extends FlameGame with HasCollidables {
...
@override
Future<void> onLoad() async {
await super.onLoad();
add(ScreenCollidable());
}
}
class YourComponent extends PositionComponent with HasHitboxes, Collidable {
@override
Future<void> onLoad() async {
await super.onLoad();
// Change this if you want the components to collide with each other
// and not only the screen.
collidableType = CollidableType.passive;
addHitbox(HitboxRectangle());
}
// Do note that this doesn't work if the component starts
// to go outside of the screen but then comes back.
@override
void onCollisionEnd(Collidable other) {
if (other is ScreenCollidable) {
removeFromParent();
}
}
}
并在 update
循环中计算它:
class YourComponent extends PositionComponent with HasGameRef {
@override
void update(double dt) {
final topLeft = absoluteTopLeftPosition;
final gameSize = gameRef.size;
if(topLeft.x > gameSize.x || topLeft.y > gameSize.y) {
removeFromParent();
return;
}
final bottomRight = absolutePositionOfAnchor(Anchor.bottomRight);
if(bottomRight.x < 0 || bottomRight.y < 0) {
removeFromParent();
return;
}
}
}
我还建议您在 Flame 1.0.0 发布时立即更新到它。 :)