我正在研究Java中激光与怪物碰撞的边界框碰撞。碰撞没有问题。问题是 OneEye 类中的 Rectangle 对象是静态的!
问题 1:如果游戏中有一个怪物,这没有问题,但在我的游戏中,我将添加大量 Monster 类的实例。因此,如果我要添加多个怪物,我的矩形对象就不能是静态的。
问题 2:注意:如果 Rectangle 对象是非静态的,我的 Rectangle 的 getter 方法需要是非静态的。
但我似乎不知道如何解决这两个问题。
我的碰撞再次成功了!如果我要添加同一类的不同实例,则更多的是代码设计缺陷。总而言之,如何在当前类中引用来自不同类的实例,我正在编写代码而不在静态上下文中引用它。
这是我的两个类的代码:Laser 类和 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;
}
}
最佳答案
毫无疑问,你肯定需要走非静态路线。只需将 rect 矩形变量和 getRectangle()
方法设置为非静态即可。如果这会导致进一步的问题,那么您将需要发布这些问题的详细信息。
编辑您声明:
I tried that. But then the problem comes up: I cannot call getRectangle method (which is in my Monster class) in my Laser class.
问题不是你不能在Laser类中调用getRectangle()
,而是你不能在OneEye上调用它。一些你很少告诉我们的事情。我假设 OneEye 是一个 Monster 变量,而不是 Monster 子类。如果是后者,那么您的设计就失败了,因为您应该调用类实例上的方法,而不是类本身。
编辑2
好的,现在我看到 OneEye,我发现它是一个类,而不是一个实例。不要尝试调用此方法。相反,要么创建一个保存 Monster 对象的 oneEye 变量,要么创建一个扩展 Monster 的 OneEye 类,但无论哪种方式,都不要在类上调用 getRectangle()
。在引用 Monster 或 Monster 子类对象的变量上调用它。
关于java - Java中如何在当前类中引用不同类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14543442/