平台游戏碰撞(会穿过地面几个像素)

3

我正在尝试制作一个平台游戏。我已经有了碰撞检测代码(几乎完成),但似乎有一个错误。我尝试使用以下代码:

 for (int i = 0; i < world.ground.size(); i++) {
        if (!world.ground.get(i).intersects((int) x, (int) y, player_width, player_height + (int) dy)) {
            y += dy;
            if (dy < 4) {
                dy += 0.1;
            }
        } else {
            dy = 0;
            jumped = false;
        }
    }

但有时我的角色脚会穿过地面2或3个像素,有更好的解决方法吗?请帮忙,谢谢。


这只卡通角色的两只脚高度一样吗?这可能只是一个纯粹的外观 bug。x、y 和 dy 的数据类型是什么?有趣的代码部分是 if (dy < 4)。那是干什么用的? - Tony Ennis
我不想dy太高。所以你可以把4看作终端速度。x、y和dy都是双精度浮点数。脚的高度是相同的。 - Mertcan Ekiz
所以如果 dy 开始为 .1,当 i 从 0 增加到 world.ground.size() 时,你可以接受 dy 增加到 4 吗? - Tony Ennis
只有当玩家不与地面相交时,它才会增加,所以我对此感到满意。 - Mertcan Ekiz
1个回答

3
看起来你正在使用后验(离散)碰撞检测。这会导致你的对象每次都会穿过一点,因为它只有在触碰或穿透时才会激活。你可以考虑将其转换为先验(连续)碰撞检测。这样,它就不会穿过地面,因为它在碰撞之前进行检查,然后调整速度或位置以避免穿透。
如果你不想折腾这种方法,你也可以添加一个修正函数,在绘制之前执行。
void foo()
{
      //check if below ground
      //if yes, displecement upwards until it is above enough
      //now you can paint
      //return
}

我看到你实现了这个:

  what_you_need_to_make_it_above_ground=(ground_y-feet_y);


  //im not sure if dy is ground level so i added second boolean compare

  if ((dy < 4)||(ground_y>feet_y)) {
                 dy += 0.1; // this isnt enough. should be equal to:
                 dy +=what_you_need_to_make_it_above_ground;
                 dy +=if_there_are_other_parameters_think_of_them_too;

              }

好的,那么我该如何实现这个优先碰撞检测呢?一些伪代码会有所帮助。 - Mertcan Ekiz
刚刚为 的实现添加了一些伪代码,因为我不想取消你的程序。 - huseyin tugrul buyukisik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接