【问题标题】:Remove an Actor in Greenfoot if he´s on the top如果他在顶部,则删除 Greenfoot 中的 Actor
【发布时间】:2022-01-04 17:06:48
【问题描述】:

我正在使用 Greenfoot 在 Java 中构建自己的 Space Invaders,并且我有一艘发射外星人的宇宙飞船,但子弹停在地图顶部并停留在那里,所以我编写了这个方法,如果它应该删除子弹达到顶部,但它不起作用。有什么问题?

public void disappearIfOnTop() {
    Actor Bullet = getOneIntersectingObject(Actor.class);
    getY();

    if(getY() == 0) {
        World world;
        world = getWorld();
        world.removeObject(Bullet);
    }
}

编辑:如果他们击中另一个卡在顶部的子弹,他们就会被移除。

【问题讨论】:

    标签: java greenfoot


    【解决方案1】:

    如果没有其他演员,getOneIntersectingObject() 方法将返回null

    您可能需要检查一下以确保:

    public void disappearIfOnTop() {
        if (getY() == 0) {
            Actor bullet = getOneIntersectingObject(Actor.class);
            if (bullet == null) {
                setLocation(getX(), 50); // move down if no other is around
            } else {
                setLocation(getX(), 100); // move further down if another is around
            }
        }
    }
    

    如果getOneIntersectingObject() 方法返回一个actor 的引用,则您当前的方法是删除那个 一个,而不是Y=0 的那个。 (顺便说一句,不要使用以大写字母开头的变量名。按照惯例,这是为类保留的。)

    您可以将方法简化为:

    public void disappearIfOnTop() {
        if (getY() == 0) {
            getWorld().removeObject(this);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-19
      • 2022-01-11
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      • 2017-10-25
      相关资源
      最近更新 更多