我目前正在使用Java开发没有库的2D平台程序。当播放器左右移动,直线移动时,碰撞正常工作。但是,当玩家跌落或跳跃时与瓷砖水平碰撞时,玩家会进入瓷砖内部并可以在其中向左/向右移动,但不会掉落并且不能跳跃。
这里有我的碰撞检测代码:
protected boolean collision(double xa, double ya)
{
boolean solid = false;
for (int c = 0; c < 4; c++)
{
int xt = (int) Math.round(((x + xa) + c % 2 * 9 - 1) / Tile.SIZE);
int yt = (int) Math.round(((y + ya) + c / 2 * 14 - 2) / Tile.SIZE);
if (level.getTile(xt, yt).isSolid()) solid = true;
}
return solid;
}
移动方法:
public void move(double xa, double ya)
{
if (!collision(xa, ya))
{
x += xa;
}
if (!collision(0, ya))
{
y += ya;
}
}
和播放器更新方法:
public void update()
{
boolean left = Keyboard.isKeyDown(KeyEvent.VK_A);
boolean right = Keyboard.isKeyDown(KeyEvent.VK_D);
boolean jump = Keyboard.isKeyDown(KeyEvent.VK_SPACE);
boolean mousePressed = Mouse.isMousePressed();
double xa = 0;
double ya = 0;
if (left && !right)
{
moving = true;
xFlip = true;
xa -= currentSpeed;
}
else if (right && !left)
{
moving = true;
xFlip = false;
xa += currentSpeed;
}
else
{
moving = false;
}
if (onGround)
{
yVel = 0;
currentSpeed = speed;
jumped = false;
this.jump.reset();
if (jump)
{
yVel = -5;
currentSpeed = speed + jumpSpeedIncrease;
run.reset();
idle.reset();
idleTimer = 0;
jumped = true;
}
else if (moving)
{
run.update();
sprite = run.getSprite();
idle.reset();
idleTimer = 0;
}
else if (!moving)
{
if (idleTimer <= idleSleepTimeSeconds * Main.getDesiredUps())
{
idleTimer++;
idle.update();
sprite = idle.getSprite();
}
else
{
idle.reset();
sprite = Sprite.PLAYER_IDLE4;
}
run.reset();
}
if (!punching && mousePressed && ++punchTimer >= punchTimerSeconds * Main.getDesiredUps())
{
punchTimer = 0;
punching = true;
}
if (punching && (!punch.finished() || punch.isReset()))
{
punch.update();
sprite = punch.getSprite();
}
else if (punching && punch.finished())
{
punching = false;
punch.reset();
}
}
else
{
yVel += .25;
if (!jumped)
{
ya += yVel;
}
if (collision(0, yVel)) yVel = 0;
}
if (jumped)
{
this.jump.update();
sprite = this.jump.getSprite();
ya += yVel;
}
groundYA = ya + .5;
onGround = collision(0, groundYA) && groundYA > 0;
move(xa, ya);
}
以下是我发布的有关发生的确切视频: https://www.youtube.com/watch?v=JIoKMuTeuow
如果有人有任何想法,请告诉我!
编辑:修复了帖子中的一些语法并添加了更多标签