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

Java游戏碰撞检测(侧面碰撞)与矩形,java,collision-detection,Java,Collision Detection,我一直在写一个游戏引擎,我的演员类有问题。我想确定与矩形(上面)和矩形边的碰撞。我为他们写了两种方法 public boolean isLeftCollision(Actor-Actor){ 布尔布尔布尔=假; 矩形LeftBounds=新矩形(x,y,x-velocity,image.getHeight(null)); bool=LeftBounds.intersects(actor.getBounds()); 返回布尔; } 公共布尔isRightCollision(参与者){ 布尔布尔布尔

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

public boolean isLeftCollision(Actor-Actor){
布尔布尔布尔=假;
矩形LeftBounds=新矩形(x,y,x-velocity,image.getHeight(null));
bool=LeftBounds.intersects(actor.getBounds());
返回布尔;
}
公共布尔isRightCollision(参与者){
布尔布尔布尔=假;
矩形RightBounds=新矩形(x+image.getWidth(null),y,image.getWidth(null)+速度,image.getHeight(null));
bool=RightBounds.intersects(actor.getBounds());
返回布尔;
}
这里的速度是下一步的运动


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

我承认我几乎看不懂你的代码,如果我的答案没有帮助,我很抱歉。我猜想碰撞的速度会产生误差。根据您检查的频率和velocity保持的值,您可能会注册尚未发生的碰撞

我将分两步进行碰撞检测

  • 碰撞试验
  • 确定它是在上面还是在一边
  • 下面是一些伪代码:

    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 self_shape=this.getBounds();
    矩形other_shape=actor.getBounds();
    布尔碰撞=自_形。相交(其他_形);
    如果(碰撞){
    //创建两个新变量self\u centerx和self\u centery
    //以及另外两个新变量,即_centerx和_centery
    //让它们指向物体中心的坐标
    //对应矩形
    
    bool left=self_centerx-other_centerx记住矩形的第三个参数是宽度,而不是另一侧的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());
    }
    

    (假设“速度”是向左或向右移动的(正)距离,则只调用移动方向的方法)

    @stas如何添加错误日志。运行程序,复制并粘贴错误。向右移动的速度为正,向左移动的速度为负吗?@RussellZahniser抱歉地说,这里的速度是向左或向右移动的像素数。它总是正的。