java2d碰撞响应方法
最近,我一直在玩基本的2D java游戏编程,并一直有很多乐趣发现我自己的东西,但我提出了一个问题。我已经创建了一个简单的碰撞方法,这个方法有很多错误。所以我的问题是,当玩家与方块碰撞时,如何改变他们的x和y。我尝试了下面的代码,它可以识别玩家何时发生碰撞,但它没有将他的x和y设置为x,y设置为tempx和y。代码:java2d碰撞响应方法,java,2d,collision-detection,collision,Java,2d,Collision Detection,Collision,最近,我一直在玩基本的2D java游戏编程,并一直有很多乐趣发现我自己的东西,但我提出了一个问题。我已经创建了一个简单的碰撞方法,这个方法有很多错误。所以我的问题是,当玩家与方块碰撞时,如何改变他们的x和y。我尝试了下面的代码,它可以识别玩家何时发生碰撞,但它没有将他的x和y设置为x,y设置为tempx和y。代码: private void update(){ tempx = player.getX(); tempy = player.getY(); collided
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;
}
问题似乎出在您的更新方法中
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");
}
}
由于将玩家的位置设置为其当前所在的位置,因此根本看不到角色移动到任何位置。您可能需要更改tempx
和tempy
tempx = player.getX() + 10;
tempy = player.getY() + 10;
更新
对于更新过程是如何工作的,似乎存在一些困惑
考虑以下几点:
- 字符从(0,0)开始
- 位于(2,2)中心的某个物体会引起碰撞
两个x现在都是0tempx=player.getX()
tempy=player.getY()
- 检查碰撞,没有
- 因为没有碰撞,所以更新播放器。(我假设update方法移动字符(+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)处有一个
- 因为发生了冲突,所以可以将角色“移动”到tempx和tempy,但是tempx和tempy的值与character.getX和character.getY的值相同
如果希望在角色更新的整个移动过程中保持不变,则必须将
tempx
和tempy
设置为等于更新循环外的角色位置。tempx和tempy不是玩家原始的x和y坐标吗?因此当调用player.setX((int)tempx)和player.setY((int)tempy)时是的,这是我想做的。它设置了tempx或者x的初始值,这样如果它没有碰撞,它就可以改变玩家的位置。但是如果它发生碰撞,那么它会将玩家的位置重置为在碰撞之前的位置update@user2280906但是update()
方法可能每秒调用数百次。每次调用update()
方法时,它都会获取播放机的新的当前位置,并将其设置为等于tempx。在任何给定点,tempx都将与player.getX()相同;
@user2280906因此,如果没有冲突,它会更新播放机的位置。下次它会将tempx和tempy的值重置为播放机的新位置,然后再次检查是否有冲突。如果有冲突,它会将播放机的当前值设置为tempx和tempy,这仍然是当前值player.getX()
和player.getY();
你一直到最后都是正确的。如果发生碰撞,它会将玩家的位置重置为移动前的位置。他实际移动的位置在玩家中。update();tempx和tempy是玩家移动前的状态,因此如果发生碰撞,它可以将x和y设置为玩家移动前的状态。顺便说一句,感谢所有帮助,感谢您花时间帮助我解决此问题。
tempx = player.getX() + 10;
tempy = player.getY() + 10;