1

我正在研究激光与 Java 中的怪物碰撞的边界框碰撞。碰撞没有问题。问题是 OneEye 类中的 Rectangle 对象是静态的!

问题 1:如果游戏中有一个怪物,这没问题,但在我的游戏中,我将添加很多 Monster 类的实例。因此,如果我要添加多个怪物,我的 Rectangle 对象就不能是静态的。

问题 2:注意:如果 Rectangle 对象是非静态的,我的 Rectangle 的 getter 方法需要是非静态的。

但我似乎无法弄清楚如何解决这两个问题。

再次,我的碰撞有效!如果我要添加同一个类的不同实例,这更像是一个代码设计缺陷。总而言之,我如何在当前类中引用来自不同类的实例我正在编写代码而不在静态上下文中引用它。

这是我的两个类的代码:激光类和 OneEye 类

public class Laser {

/* use a bounding box 
     * to test collision detection
     * 
     */
    private Rectangle rect;

   public void update(long milliseconds) {

// surround a bounding box around the laser
        rect = new Rectangle((int)position.x,(int)position.y,this.getWidth(),this.getHeight());
        // collision against the OneEye monster
        if(rect.intersects(OneEye.getRectangle()))
        {
            Game.getInstance().remove(this);
        }


}

public class OneEye {

/*
     * use bounding box
     * for collision 
     * detection
     */
    private static Rectangle rect;

public void update(long milliseconds) {

        // surround a bounding box around the oneEye monster
        rect = new Rectangle((int)position.x,(int)position.y,this.getWidth(),this.getHeight());
}

// can be useful for collision detection
public static  Rectangle getRectangle()
    {
        return rect;
    }
}
4

1 回答 1

1

毫无疑问,您绝对需要走非静态路线。只需使 rect Rectangle 变量和getRectangle()方法非静态。如果这会导致进一步的问题,那么您将需要发布这些问题的详细信息。

编辑你状态:

我试过了。但是问题来了:我不能在我的 Laser 类中调用 getRectangle 方法(在我的 Monster 类中)。

问题不在于你不能getRectangle()在 Laser 类中调用,而在于你不能在 OneEye 上调用它。你很少告诉我们的事情。我假设 OneEye 是 Monster变量而不是 Monster 子类。如果是后者,那么您的设计就失败了,因为您应该在类实例上调用方法,而不是在类本身上。

编辑 2
好的,现在我看到 OneEye,我看到它是一个类,而不是一个实例。不要试图以此调用方法。相反,要么创建一个包含 Monster 对象的 oneEye 变量,要么创建一个扩展 Monster 的 OneEye 类,但无论哪种方式,都不要调用getRectangle()类。在引用 Monster 或 Monster 子类对象的变量上调用它。

于 2013-01-27T01:18:02.890 回答