XNA collision in 3D



我一直试图在我的程序中获得碰撞检测。在我的程序中,一个立方体里面有一个球。我想让球在立方体内部弹跳,如果我的立方体上有一个洞,我想让它掉出来。

我现在是这样做的:

protected void Bounce()
    {
        if (ballPosition.X >= boxWidth || ballPosition.X <= -boxWidth)
            modelVelocity.X *= -1;
        if (ballPosition.Y >= boxHeight*4.18 || ballPosition.Y <= -boxHeight)
            modelVelocity.Y *= -1;
        if (ballPosition.Z >= boxLength || ballPosition.Z <= -boxLength)
            modelVelocity.Z *= -1;
    }

但这不是很好地工作,并在我实现重力时出现故障。它穿过两边。它不会呆在盒子里。那么如何检测碰撞,或者检测一个角度,使它在一个特定的方向上反弹如果有倾斜的墙壁?

要检测球和框何时相交,可以分别使用BoundingSphere和BoundingBox。然后使用BoudningBox.Contains()方法和一种不同的Containment类型来检测球和框的边缘何时相交。

举个例子:

void CollisionDetection()
{
    if (!boxBoundingBox.Contains(ballBouningSphere, ContainmentType.Contains)) 
    //if the box doesn't completely contain the ball they are overlapping
    {
        //Collision happened.
    }
}

然后对于洞,你可能想要创建一个自定义对象holes,如果球和盒子重叠,检查球是否在洞里,如果是,取消碰撞。这些只是一些想法。HTH

使用轴的逻辑:当X> targetX和X x轴碰撞确认。但这并不意味着存在碰撞:你必须对y轴做同样的事情(对于3D也是如此)所以你得到:

public bool collision(Vector3 pos, Vector3 dimensions, Vector3 targetPos, 
Vector3 targetDimensions)
{
   return (pos.X + dimensions.X > targetPos.X &&
           pos.X < targetPos.X + targetDimensions.X &&
           pos.Y + dimensions.Y > targetPos.Y &&
           pos.Y < targetPos.Y + targetDimensions.Y &&
           pos.Z + dimensions.Z > targetPos.Z &&
           pos.Z < targetPos.Z + targetDimensions.Z);
}

最新更新