gpt4 book ai didi

Java平滑2D矩形碰撞?

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:52 25 4
gpt4 key购买 nike

嘿伙计们,我正在制作一个迷宫游戏,我正在尝试找出如何使 2D 碰撞变得平滑。目前,我想出了一些非常糟糕的碰撞代码,因为我还没有完成这部分,而且它有故障,有时会进入墙内,然后你就无法出去。

我的代码:

    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)) {
if(player.xspeed == 1) {
player.xspeed = 0;
player.x -= 1.2;
} else {

if(player.xspeed == -1) {
player.xspeed = 0;
player.x += 1.2;
}
else
if(player.yspeed == 1) {
player.yspeed = 0;
player.y -= 1;
} else {
if(player.yspeed == -1) {
player.yspeed = 0;
player.y += 1;
}
}

}
}

}

}

什么是更好的碰撞方法?这是我将拥有的 map 类型的图片:

enter image description here

编辑:

新的碰撞代码:

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

}

Action 代码:

    public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();

if(key == KeyEvent.VK_LEFT) {

xspeed = -1;

} else {
if(key == KeyEvent.VK_RIGHT) {

xspeed = 1;

} else {
if(key == KeyEvent.VK_UP) {
yspeed = -1;
} else {
if(key == KeyEvent.VK_DOWN) {
yspeed = 1;
}
}
}
}
}

感谢您给我的任何帮助。

最佳答案

您可以使用Rectangle.createIntersection(Rectangle)

如果玩家向正方向移动,只需从他的位置中减去所得矩形的宽度和高度,如果他向负方向移动,则将它们相加。

不要将速度设置为零,这可能会导致播放器挂起。

编辑

if (playerRectangle.intersects(wallRectangle) {
Rectangle intersection = (Rectangle) playerRectangle.createIntersection(wallRectangle);

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

编辑2

据我所知,keyPressed 仅在按下某个键时触发,而在松开键时不会触发。尝试这样:

private boolean up, down, left, right;

public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KEyEvent.VK_UP) {
up = true;
}

...
}

public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KEyEvent.VK_UP) {
up = false;
}

...
}


// Call this in the mainthread
public void updateMovement() {
if (up) {
player.xspeed = 1;
}

...
}

因此,在每一帧中,您都会更新运动、移动玩家,然后检查碰撞。

关于Java平滑2D矩形碰撞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7753549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com