【问题标题】:Why removing other sprite after collision not working in Flame?为什么在碰撞后移除其他精灵在火焰中不起作用?
【发布时间】:2022-01-17 18:12:35
【问题描述】:

我在游戏中有两个精灵,例如玩家和敌人。碰撞检测后为什么remove(Component)方法不起作用?

import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame/geometry.dart';
import 'package:flutter/material.dart';

void main() async {
  runApp(GameWidget(
    game: CGame(),
  ));
}

class CGame extends FlameGame with HasCollidables {
  @override
  Future<void>? onLoad() async {
    add(Enemy());
    add(Player());

    return super.onLoad();
  }
}

class Enemy extends SpriteComponent with HasGameRef, HasHitboxes, Collidable {
  Enemy() : super(priority: 1);

  @override
  Future<void>? onLoad() async {
    sprite = await Sprite.load('crate.png');
    size = Vector2(100, 100);
    position = Vector2(200, gameRef.size.y / 3 * 2);
    anchor = Anchor.center;
    addHitbox(HitboxRectangle());

    return super.onLoad();
  }
}

class Player extends SpriteComponent with HasGameRef, HasHitboxes, Collidable {
  @override
  Future<void>? onLoad() async {
    sprite = await Sprite.load('player.png');
    size = Vector2(100, 100);
    position = Vector2(0, gameRef.size.y / 3 * 2);
    anchor = Anchor.center;
    addHitbox(HitboxRectangle());

    return super.onLoad();
  }

  @override
  void update(double dt) {
    position += Vector2(1, 0);
  }

  @override
  void onCollision(Set<Vector2> intersectionPoints, Collidable other) {
    if (other is Enemy) {
      print('Player hit the Enemy!');

      remove(Enemy());  //<== Why this line is not working?
    }
  }
}

【问题讨论】:

    标签: flutter flame


    【解决方案1】:

    您正在尝试移除一个敌人组件的新实例,您必须移除与您发生碰撞的特定实例,在本例中为other。 如果您在尝试删除子组件的组件上执行remove,您还想从添加它的游戏中删除other

      @override
      void onCollision(Set<Vector2> intersectionPoints, Collidable other) {
        if (other is Enemy) {
          other.removeFromParent();
          // It can also be done like this since you have the `HasGameRef` mixin
          // gameRef.remove(other);
        }
      }
    }
    

    【讨论】:

    • 哦,和OOP有关。谢谢卢卡斯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    相关资源
    最近更新 更多