我正在用Java制作2D平台游戏,我正在努力解决碰撞问题。它主要起作用,但每当我登陆平台时,角色都会向下移动几个像素。我的代码托管在github。与此问题相关的类是World.java
和GameCharacter.java
我的碰撞检查代码(在无限循环上运行):
void collisionCheck() {
for (GameCharacter gc : Characters) {
gc.canJump = false;
gc.canWallJump = false;
}
for (Platform g : Levels.get(Level)) {
Rectangle tmprect = ((Rectangle) g.clone());
tmprect.grow(RectScale, RectScale);
for (GameCharacter gc : Characters) {
if (gc.intersects(tmprect)) {
if (g.x + RectScale > gc.gx + gc.width) {
gc.isLeft = true;
gc.isMiddleX = false;
} else if (g.x + g.width < gc.gx + RectScale) {
gc.isLeft = false;
gc.isMiddleX = false;
} else {
gc.isMiddleX = true;
}
if (g.y + RectScale > gc.gy + gc.height) {
gc.isTop = true;
gc.isMiddleY = false;
} else if (g.y + g.height < gc.gy + RectScale) {
gc.isTop = false;
gc.isMiddleY = false;
} else {
gc.isMiddleY = true;
}
if (gc.isMiddleX && gc.isMiddleY) {
if (gc.isTop) {
gc.gmy = 0;
gc.gy -= 1;
} else {
gc.gmy = 0;
gc.gy += 5;
}/*
if (gc.isLeft) {
gc.gmx = 0;
gc.gx -= 1;
} else {
gc.gmx = 0;
gc.gx += 1;
}*/
} else if (gc.isMiddleY) {
if (gc.isLeft) {
if (gc.gmx > 0) {
gc.gx -= 1;
gc.gmx = 0;
}
} else if (gc.gmx < 0) {
gc.gmx = 0;
gc.gx += 1;
}
} else if (gc.isMiddleX) {
if (gc.isTop) {
if (gc.gmy > 0) {
gc.gmy = 0;
}
} else if (gc.gmy < 0) {
gc.gmy = 0;
}
}
if (gc.isTop && gc.isMiddleX) {
gc.canJump = true;
}
if (g.Props.contains("w") && gc.isMiddleY) {
gc.canWallJump = !gc.isMiddleX;
}
}
}
}
try {
Thread.sleep(CollisionDelay-1);
} catch (InterruptedException ex) {
System.err.println("ERROR");
}
}
我的角色更新(在单独的线程上运行):
public void update() {
ScreenX=world.Levels.get(world.Level).xs;
ScreenY=world.Levels.get(world.Level).ys;
if (gy >= ScreenY - (height + 10)) {
gmy = 0;
canJump = true;
gy = ScreenY - (height + 10);
} else if (gy < 0) {
gmy = 0;
gy = 0;
} else {
gmy += 2;
}
if (gx + width > ScreenX) {
gx = ScreenX - width;
gmx = 0;
} else if (gx < 0) {
gx = 0;
gmx = 0;
} else if (RightKeyPressed) {
gmx += 0.07;
} else if (LeftKeyPressed) {
gmx -= 0.07;
}
if (SpacePressed && (canJump || canWallJump)) {
if (canWallJump && !canJump) {
if (isLeft && RightKeyPressed) {
gmx = -6;
gmy = -220.0;
} else if (!isLeft && LeftKeyPressed) {
gmx = 6;
gmy = -220.0;
}
} else {
gmy = -220.0;
}
}
gmx *= 0.97;
gx += gmx;
gy += gmy / 70;
x = (int) gx;
y = (int) gy;
try {
Thread.sleep(world.getSpeed());
} catch (InterruptedException ex) {
}
}