Java 2D 碰撞? [英] Java 2D Collision?
问题描述
大家好,我正在制作一个 2D Java 游戏,我正在尝试弄清楚如何制作一个好的碰撞代码.我目前正在使用以下代码:
Hey guys i'm making a 2D java game and i'm trying to figure out how to make a good collision code. I am currently using the following code:
public void checkCollision() {
Rectangle player_rectangle = new Rectangle(player.getX(),player.getY(),32,32);
for(Wall wall : walls) {
Rectangle wall_rectangle = new Rectangle(wall.getX(), wall.getY(), 32,32);
if (player_rectangle.intersects(wall_rectangle)) {
Rectangle intersection = (Rectangle) player_rectangle.createIntersection(wall_rectangle);
if (player.xspeed > 0) {
player.x -= intersection.getWidth();
}
if (player.yspeed > 0) {
player.y -= intersection.getHeight();
}
if (player.xspeed < 0) {
player.x += intersection.getWidth();
}
if (player.yspeed < 0) {
player.y += intersection.getHeight();
}
Print(Integer.toString(intersection.width) + ", " + Integer.toString(intersection.height));
}
}
}
使用此代码,如果您按下一个按钮,它就可以正常工作,但是如果按下并向左按下,例如玩家将向某个随机方向飞去.
With this code it works fine if you are press one button but if press down and left for example the player will fly off in some random direction.
这是我拥有的地图类型的图片:
Here is a picture of the types of maps I have:
推荐答案
你的主要问题是假设玩家直接撞到墙上.考虑有一个墙壁矩形 (100,100,32,32) 并且玩家位于 (80,68,32,32) 的情况.玩家正在向下和向左移动,因此 player.xspeed <;0 和 player.yspeed > 0;假设玩家的下一个位置是 (79,69,32,32).交点是 (100,100,11,1).
Your main problem is in assuming that the player is running directly into the wall. Consider the case where there is a wall rect (100,100,32,32) and the player is at (80,68,32,32). The player is moving down and to the left, so player.xspeed < 0 and player.yspeed > 0; say the next position for the player is (79,69,32,32). The intersection is then (100,100,11,1).
请注意,尽管玩家向左(以及向下)移动,但墙实际上位于玩家的右侧.这一行:
Note that although the player is moving left (as well as down) the wall is actually to the right of the player. This line:
if (player.xspeed < 0) {
player.x += intersection.getWidth();
}
... 导致 player.x 突然跳转到 90.
... causes player.x to be set to 90 in a sudden jump.
您可以做的一件事是检查玩家的左侧是否包含在交叉点中,即
One thing you could do is check that the player's left-hand side was contained in the intersection, i.e.
if (player.xspeed < 0 && player.x >= intersection.x) {
player.x += intersection.getWidth();
}
显然其他方向也需要做类似的事情.
Obviously a similar thing needs to be done for the other directions too.
这篇关于Java 2D 碰撞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!