c++ - 2D Box Collision - 这是对的吗?

标签 c++ 2d

好吧,我有一个 2D 盒子碰撞代码,它基本上循环遍历名为“ block ”的列表中的每个 block ,它会检查我是否靠近侧面等等。

除了 block 的底部,它工作得很好。当我跳向底部时,我希望我的播放器简单地“反弹”。它这样做,但它是非常有问题的。 这很难解释,所以我希望你们能找出我的底部碰撞代码有什么问题。

全文如下:

for(unsigned int i = 0; i<blocks.size(); i++){
Block &b = blocks.at(i);
if(!b.passable==true){
    //Check if we are on the sides
    if(y + height + vspeed >= b.worldY+2 && y + vspeed <= b.worldY+b.height)
    {
        //Right side
        if(x + hspeed <= b.worldX+b.width-1  && x + hspeed > b.worldX+b.width + hspeed-2)
        {
         x = b.worldX + b.width; hspeed = 0;
        }
        //Left side    
        if(x + width + hspeed >= b.worldX +1 && x + width + hspeed <= b.worldX + hspeed + 2)
        {
         x = b.worldX - width; hspeed = 0;
        }
    }

    //Check if we are on the top or the bottom
    if(x + width + hspeed >= b.worldX+2 && x + hspeed <= b.worldX+b.width-2)
    {
        if(y + height + vspeed >= b.worldY && y + height + vspeed <= b.worldY + vspeed + 1 && jumpstate=="falling")
            {
              y = b.worldY - height; jumpstate.assign("ground"); vspeed = 0;
            }

        if(y + vspeed <= b.worldY + b.height && y + vspeed >= b.worldY + b.height + vspeed - 1 && jumpstate=="jumping")
        {
            y = b.worldY + b.height; jumpstate.assign("falling"); vspeed = 0;
        }

        }
    }
}

最佳答案

我猜你应该设置 vspeed = -vspeed;而不是 vspeed = 0 .完全弹性弹跳意味着速度在盒子的侧面得到镜像。

如果将其设置为零,则根据执行更新的顺序,您可能不会在一帧内移动。并且由于您使用 <=>=对于边界检查,您仍将在下一帧的框内,再次调用弹跳行为,并卡在您的头上粘在 block 上。

关于c++ - 2D Box Collision - 这是对的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6561341/

相关文章:

c++ 取消引用迭代器时 x++ 和 x = x + 1 之间的区别

ios - Unity iOS Build 尺寸很大

c++ - 如何将动态二维数组传递给 C++ 中的函数

c++ - 如何检测 Qt 中的全局键序列按下?

c++ - 为什么我的out_of_range异常没有被捕获

c++ - 立方体旋转 - OpenGL

c++ - 开发 C++ 链接器错误

opengl-es - 优化基于 OpenGL 的动画/可缩放 2D UI 渲染的策略

c# - 通过使用 2D 变换旋转图像填充矩形来模拟透视

c++ - 如何在 2D opengl 中进行拾取?