【问题标题】:XNA collision in 3D3D 中的 XNA 碰撞
【发布时间】:2014-03-14 12:49:15
【问题描述】:

我一直在尝试在我的程序中进行碰撞检测。在我的程序中,立方体内有一个球。我希望球在立方体内反弹,如果我的立方体上有一个洞,我希望它掉出来。

我现在是如何进行“碰撞”的:

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

但是当我实现重力时,这并不能很好地工作并且出现故障。它穿过两侧。它不会留在盒子里。那么如何检测碰撞,并可能检测到一个角度,如果有倾斜的墙壁,它会在某个方向反弹?

【问题讨论】:

  • ballPosition.X 和 .Y 引用在哪里?如果不使用某种半径,这些值无法检测到球体的所有边缘。很有可能您在上面提到的位置实际上是球体的中心,而您看到的是边缘被剪掉。你必须做数学才能找到球的边缘。

标签: c# 3d xna


【解决方案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,如果球和盒子重叠,则检查球是否在孔中,如果是,则取消碰撞。这些只是一些想法。高温

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-08-10
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      • 2014-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多