问题描述
所以我正在研究碰撞检测代码,我所做的是当用户矩形与不能移动的矩形重叠时,我阻止他们移动。因此,如果我向右移动,我撞墙,我不能前进。这很有效。然而,如果在我撞到那堵墙之后,我想向下或向上移动那个点,我会卡住。
So I'm working on a collision detection code and what i do is when the user rectangle overlaps the rectangle where they cant move, I stop them from moving. So if im moving right and I hit a wall i cant move forward. This works. However if after i hit that wall, I want to move down or up form that point, I get stuck.
这是我检查用户是否已经进行了整理的方式
This is how i check if the user has colidded
private void checkCollision() {
for (int x = 0; x < amount; x++) {
if (collsionRect[x].overlaps(user)) {
Gdx.app.log(ChromeGame.LOG, "Overlap");
xD = 0;
yD = 0;
}
}
}
这就是我搬家的方式我的用户
And this is how I move my user
private void moveUser() {
// camera.translate(xD, yD);
player.translate(xD, yD);
camera.position.set(player.getX(), player.getY(), 0);
// Gdx.app.log(ChromeGame.LOG, player.getX() + "," + player.getY());
user = new Rectangle(player.getX(), player.getY(), player.getWidth(),
player.getHeight());
checkCollision();
}
在我的渲染方法中,我一直调用move userMove方法直到我放开键盘将xD,yD变为零
In my render method I keep calling the move userMove method till I let go of the keyboard wher eit turns the xD,yD to zero
推荐答案
问题是你检查矩形是否重叠。这意味着你的角色不会碰撞,除非他的某些部分已经在墙内,然后他就会停止移动。下次你要移动角色时他已经碰撞(他的一部分在墙内)所以 checkCollision()
将设置 xD ,yD
为0,你的角色不会移动。
The problem is that you check if rectangles overlap. This means that your character is not colliding unless some part of him is already inside the wall, then he stops moving. The next time you want to move the character he is already colliding (a part of him is inside the wall) and so checkCollision()
will set xD, yD
to 0 and your character won't move.
最简单的解决办法是做一个假动作(插值)并检查这一新举动是否会让他发生碰撞,如果他发生碰撞,你根本就不接受这一新动作。在伪代码中
The easiest solution to this is to make a "fake" move (interpolation) and check if this new move will make him collide, if he will collide you simply don't accept this new move. In pseudocode
new position = player.x + deltaX, player.y+deltaY
create new rectangle for player from new position
check collision with new rectangle
if not collide player.x += deltaX, player.y+=deltaY
这篇关于在重叠时,玩家会被卡住libgdx矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!