我正在用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() 。
最佳答案
你可以这样做:
public boolean collide(HasBounds a, HasBounds b){...
使用接口(interface):
public interface HasBounds{
Rectangle getBounds();
}
您应该在对象上定义Arrow
、Enemy
等...(您可能已经有适合于此的对象层次结构)。
关于java - 减少 Java 游戏中碰撞方法的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15312820/