Java 2D碰撞响应方法

时间:2014-03-21 04:18:19

标签: java 2d collision-detection collision

最近我一直在玩基本的二维java游戏编程,并且我自己发现了很多乐趣,但我想出了一个问题。我已经创建了一个非常错误的简单碰撞方法。所以我的问题是当玩家与一个区块碰撞时如何改变玩家的x和y。我已经尝试了下面的代码并且它识别出玩家何时发生碰撞但是没有将他的x和y设置为x和y来设置tempx和y。代码:

private void update(){
    tempx = player.getX(); 
    tempy = player.getY();
    collided = checkCollision();
    if(collided == false){
        player.update();
    }
    else if(collided){
        player.setX((int)tempx);
        player.setY((int)tempy);
        System.out.println("COLLIDED");
    }
}

private boolean checkCollision(){
    for(int i = 0; i < tiles.size(); i++){
        Tile t = tiles.get(i);
        Rectangle tr = t.getBounds();
        if(tr.intersects(player.getBounds())){
            return tr.intersects(getBounds());
        }
    }
    return false;
}

正在检测到碰撞但是玩家x和y没有相应地改变。如果您需要更多代码或有任何问题,请询问。感谢您的帮助:))

P.S。我尝试过添加重力,碰撞只适用于块顶部,如果有任何帮助

以下是player.update()方法:

@Override
public void keyPressed(KeyEvent e){
    int k = e.getKeyCode();
    if(k != 0){
        if(k == KeyEvent.VK_W){
            y -= vy;
        }
        else if(k == KeyEvent.VK_A){
            x -= vx;
        }
        else if(k == KeyEvent.VK_S){
            y += vy;
        }
        else if(k == KeyEvent.VK_D){
            x += vx;
        }
    }
}
public void update(){

}

1 个答案:

答案 0 :(得分:1)

问题似乎出现在您的更新方法中。

private void update(){
    tempx = player.getX(); // tempx now is the same as the players x location
    tempy = player.getY();
    collided = checkCollision();
    if(collided == false){
        player.update();
    }
    else if(collided){
        player.setX((int)tempx);  // you set players location equal to temp, which is 
        player.setY((int)tempy);  // already the players location
        System.out.println("COLLIDED");
    }
}

由于您将玩家位置设置为等于当前位置,因此您根本不会看到角色移动到任何位置。您可能希望更改tempxtempy

的值
tempx = player.getX() + 10; 
tempy = player.getY() + 10;

<强>更新

关于更新过程如何运作似乎存在一些混淆。

请考虑以下事项:

  • 字符从(0,0)
  • 开始
  • (2,2)chich的某个物体会导致碰撞

鉴于上述情况,您的更新方法和IN THIS ORDER

中会发生以下情况
  • tempx = player.getX()这两个x现在都是0
  • tempy = player.getY()这两个人现在都是0
  • 检查碰撞,没有
  • 由于没有碰撞,玩家更新。 (我假设更新方法会移动字符(+ 1,+ 1)。所以字符现在位于(1,1)处。
  • tempx和tempy再次设置为getX和getY。 X和Y现在都是1.现在tempx和tempy也是1
  • 没有碰撞,因此字符被更新(移动)为(2,2)
  • tempx和tempy设置为getX和getY。 X和Y现在都是2,所以tempx和tempy也是2。
  • 检查碰撞,确实存在一个(2,2)
  • 因为碰撞你然后移动&#34; tempx和tempy的字符,但是tempx和tempy与character.getX和character.getY的值相同。

如果您希望它们在更新的字符更新动作中保持不变,则必须将tempxtempy设置为等于更新循环外的字符位置。