【问题标题】:Reducing the number of collide methods in a Java Game减少 Java 游戏中碰撞方法的数量
【发布时间】:2013-02-25 02:36:30
【问题描述】:

我正在用 java 制作一个简单的游戏,我有很多方法可以测试两个对象是否发生碰撞。对象包括人、敌人、箭、墙、硬币等。我有一堆方法可以计算可能发生的每种类型的碰撞,它们看起来像这样:

    public boolean collide(Arrow a, Enemy b)
    {
        Rectangle a1 = a.getBounds();
        Rectangle b1 = b.getBounds();
        if(a1.intersects(b1)) return true;
        else return false;
    }

是否可以创建一个泛型方法?我尝试使用对象 a 和对象 b 作为参数,但编译器发现它找不到对象的 getBounds()。

【问题讨论】:

  • 使用这些类的通用接口而不是Object。该接口必须包含一个方法Rectangle getBounds();,并且这些类必须实现它。另外,您可以将最后两行替换为return a1.intersects(b1);
  • 有关使用Shape 实例的碰撞检测示例,请参阅this answer

标签: java awt collision graphics2d java-2d


【解决方案1】:

你可以这样做:

public boolean collide(HasBounds a, HasBounds b){...

带接口:

public interface HasBounds{
  Rectangle getBounds();
}

你应该在你的对象上定义 Arrow,Enemy 等等...(你可能已经有一个适合的对象层次结构)。

【讨论】:

  • 更简单:public boolean collide(HasBounds a, HasBounds b){
【解决方案2】:

只需使用方法:Rectangle2D getShape() 创建抽象类 GameObject。此方法可能如下所示:

abstract class GameObject {
    private Image image;

    GameObject(String path) {
        try {
          image = ImageIO.read(new File(path));
        } catch (IOException ex) {}
    }

    Rectangle2D getShape() {
       return new Rectangle2D.Float(0, 0, (int)image.getWidth(), (int)image.getHeight());
    }
}

Player、Enemy、Arrow、Wall 是 GameObject 类的子类

【讨论】:

  • 这如何减少collide()方法的数量?
  • 现在你不需要用不同的碰撞修改重载碰撞()方法。取而代之的是一个方法宽度参数:(GameObject collid1, GameObject collid2)
  • 这应该是答案的一部分。构造函数和 getShape() 方法与 OP 问题无关..
【解决方案3】:

你怎么看这个..

 public boolean collide(Rectangle a1, Rectangle b1)
 {
        return a1.intersects(b1);
 }

或者可能是创建界面

public interface CanCollide {
   Rectangle getBounds();
}

并在方法中使用它...

 public boolean collide(CanCollide a, CanCollide b)
 {
     Rectangle a1 = a.getBounds();
     Rectangle b1 = b.getBounds();
     if(a1.intersects(b1)) return true;
     else return false;
 }

希望你觉得它有用。

谢谢!

@leo.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多