2013-03-09 61 views
0

我在java中做了一个简单的游戏,我有很多测试两个对象是否碰撞的方法。对象包括男人,敌人,箭头,墙,硬币等。我有一大堆的这些算不算对每一种类型可能发生碰撞的方法,他们是这样的:减少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()。

+1

使用这些类的通用接口而不是Object。该接口必须包含一个方法'Rectangle getBounds();'这些类必须实现它。另外,你可以用'return a1.intersects(b1);' – jlordo 2013-03-09 16:09:19

+0

替换最后两行,参见[本答案](http://stackoverflow.com/a/14575043/418556) '实例。 – 2013-03-09 16:23:43

回答

3

你可以这样做:

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

随着接口:

public interface HasBounds{ 
    Rectangle getBounds(); 
} 

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

+0

更简单:'公开布尔碰撞(HasBounds a,HasBounds b){' – jlordo 2013-03-09 16:13:43

+0

确实,我编辑我的答案相应 – benzonico 2013-03-09 16:15:31

+0

谢谢,这完美的作品! – Joe 2013-03-10 15:14:03

-1

只需用抽象类GameObject与方法:Rectangle2D getShape()。这种方法可能看起来像:

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()); 
    } 
} 

播放器,敌人,箭,墙会被

+0

这是如何减少'collide()'方法的数量? – jlordo 2013-03-09 16:17:51

+0

现在,您不需要为不同的碰撞修改过载collide()方法。相反,有一个方法的宽度参数:(GameObject collid1,GameObject collid2) – 2013-03-09 16:19:10

+0

这应该是答案的一部分。构造函数和'getShape()'方法与OP的问题没有任何关系。 – jlordo 2013-03-09 16:20:25

1

你觉得这是什么游戏对象类的子类..

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。