我正在高中的毕业项目中开发一个平台游戏。 然而... 我所使用的碰撞检测系统基本上是检查角色的特定部分是否与另一个块相交。
碰撞似乎工作正常,但导致一些错误,比如玩家从侧面撞击时有点卡住或者减速,或者在同时按下上下左右箭头时被弹起。
我的问题是:如何改进碰撞代码以避免此类故障并具有类似于“滑动”碰撞的效果?
这是我想要实现的碰撞效果:
(https://i.imgur.com/KB1M3bt.mp4)
(https://i.imgur.com/I44fmPc.mp4)
这是边界的预览
这是实际在游戏中的预览
(点击查看更好的质量)
我用于碰撞检测的代码:
(tempObject是玩家与之相交的块)
if(getBoundsTop().intersects(tempObject.getBoundsBottom())){
y = tempObject.getY() + height;
velY = 0;
System.out.println("Top collision");
}
if(getBoundsBottom().intersects(tempObject.getBoundsTop())){
y = tempObject.getY() - height;
velY = 0;
falling = false;
jumping = false;
//isOnBlock = true;
} else {
falling = true;
//isOnBlock = false;
}
if(getBoundsRight().intersects(tempObject.getBoundsLeft())){
x = tempObject.getX() - this.width;
}
if(getBoundsLeft().intersects(tempObject.getBoundsRight())){
x = tempObject.getX() + this.width;
}
这里是绑定方法:
public Rectangle getBounds() { return new Rectangle( (int)x, (int)y, (int)width, (int)height ); }
public Rectangle getBoundsTop() {
return new Rectangle(
(int)x,
(int)y,
(int)(width-(width*0.01f)),
(int)(height/2)
);
}
public Rectangle getBoundsBottom() {
return new Rectangle(
(int)x,
(int)(y+(height/2)),
(int)(width-(width*0.01f)),
(int)(height/2)
);
}
public Rectangle getBoundsLeft() {
return new Rectangle(
(int)x,
(int)y,
(int)((int)width*0.15f),
(int)height
);
}
public Rectangle getBoundsRight() {
return new Rectangle(
(int)
((int)x+(width-(width*0.15f))),
(int)y,
(int) ((int)width*0.15f),
(int)height
);
}
编辑:我正在使用恒定加速度速度来设置速度
acc = 2.5f;
MAX_SPEED = 10;
if(Game.keyDownMap.containsKey(KeyEvent.VK_A)){
setVelX(getVelX() - acc);
if(getVelX() < -MAX_SPEED)
setVelX(-MAX_SPEED);
} else if(Game.keyDownMap.containsKey(KeyEvent.VK_D)){
setVelX(getVelX() + acc);
if(getVelX() > MAX_SPEED)
setVelX(MAX_SPEED);
}