Java游戏碰撞检测,(侧面碰撞)与矩形



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

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

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

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

我承认我几乎看不懂你的代码,如果我的回答没有帮助,我很抱歉。我的猜测是碰撞中的速度产生了误差。根据您检查的频率和速度值,您可能会记录尚未发生的碰撞。。。

我会分两步进行碰撞检测。

  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
}

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

请记住,Rectangle的第三个参数是宽度,而不是另一侧的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());
}

(假设速度是向左或向右移动的(正)距离,并且只会调用移动方向的方法)

最新更新