2012-01-14 143 views
0

我一直在写一个游戏引擎,我的演员类有问题。我想确定一个矩形(上图)和矩形的一边的碰撞。我为他们写了两种方法。Java游戏碰撞检测,(侧面碰撞)与矩形

public boolean isLeftCollision(Actor actor) { 
    boolean bool = false; 
    Rectangle LeftBounds = new Rectangle(x, y, x-velocity, image.getHeight(null)); 
    bool = LeftBounds.intersects(actor.getBounds()); 
    return bool; 
} 

public boolean isRightCollision(Actor actor) { 
    boolean bool = false; 
    Rectangle RightBounds = new Rectangle(x+image.getWidth(null), y, image.getWidth(null)+velocity, image.getHeight(null)); 
    bool = RightBounds.intersects(actor.getBounds()); 
    return bool; 
} 

这里速度是下一步的运动。

但他们都给我错误(即错误的判断)。我该如何在演员课上解决这个问题。

+0

添加错误日志 – 2012-01-15 00:06:08

+0

@stas如何添加错误日志 – 2012-01-15 00:13:15

+0

lol。运行该程序并复制并粘贴该错误。 – 2012-01-15 00:15:57

回答

1

我承认我几乎无法读取您的代码,如果我的回答没有帮助,我很抱歉。我的猜测是碰撞中的速度会产生错误。根据您检查的频率以及速度保持的值,您可能会记录尚未发生的碰撞...

我会在两个步骤中执行碰撞检测。

  1. 试验碰撞
  2. 确定它是高于或一侧。

这里的一些伪代码:

Rectangle self_shape=this.getBounds(); 
Rectangle other_shape=actor.getBounds(); 
bool collision = self_shape.intersects(other_shape); 
if(collision){ 
    //create two new variables self_centerx and self_centery 
    //and two new variables other_centerx and other_centery 
    //let them point to the coordinates of the center of the 
    //corresponding rectangle 

    bool left=self_centerx - other_centerx<0 
    bool up=self_centery - other_centery<0 
} 

这样,你可以看看在其他演员相对于定位到你。如果它在上面或一边。

+0

感谢您的回答,它工作 – 2012-01-15 00:30:09

1

请记住,矩形的第三个参数是宽度,而不是另一边的x。所以,你真正需要的可能是这样的:

public boolean isLeftCollision(Actor actor) { 
    return new Rectangle(x - velocity, y, velocity, image.getHeight(null)) 
     .intersects(actor.getBounds()); 
} 

public boolean isRightCollision(Actor actor) { 
    return new Rectangle(x + image.getWidth(null), y, velocity, image.getHeight(null)) 
     .intersects(actor.getBounds()); 
} 

(假设速度是(正)距离向左或向右移动,只有方法要移动的方向将被称为)