二维盒子碰撞 - 这是对的吗?

时间:2011-07-03 05:55:04

标签: c++ 2d

嗯,我有一个2D盒子碰撞代码,它基本上遍历名为“Blocks”的列表中的每个块,并检查我是否靠近两侧等等。

除了块的底部之外,它的效果非常好。当我向上跳跃时,我希望我的玩家只是“反弹”。它这样做,但它是非常小故障。 这很难解释所以我希望你们能够发现我的底部碰撞代码有什么问题。

以下是整个事情:

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;
        }

        }
    }
}

2 个答案:

答案 0 :(得分:1)

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

如果将其设置为零,则根据执行更新的顺序,您可能无法在帧中移动。而且,由于您使用<=>=进行边界检查,您仍然会在下一帧的框内,再次调用弹跳行为,并将头部粘在块上。 / p>

答案 1 :(得分:0)

我对您的问题的猜测将是您的不平等检查中的负数。例如,在下降时,我猜vspeed将为负数。根据您设置盒子原点的位置,这可能意味着条件

y + vspeed <= b.worldY + b.height

总是如此。

另外,通过在速度上添加距离,您可以假设单位时间具有魔力。这会使你的代码变得脆弱,因为如果你改变这个幻数,你的方程就会出错。

尝试,

 y + vspeed*unit_time <= b.worldY + b.height

如果您想在编译时处理单位(而不是为该乘法付费),请使用boost.units

此外,

x + hspeed > b.worldX+b.width + hspeed-2

可以简化为

x > b.worldX+b.width-2

这个神奇的数字2的意义是任何人的猜测。 (例如,为什么你有

//Check if we are on the sides
if(y + vspeed <= b.worldY+b.height)

中有-2
//Check if we are on the top or the bottom
if( x + hspeed <= b.worldX+b.width-2)