簡體   English   中英

3D中的XNA碰撞

[英]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()方法和不同的一個遏制類型時,球和框邊相交來檢測。

舉個例子:

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

然后,對於孔,您可能想要創建一個自定義對象holes ,如果球和盒子重疊,則檢查球是否在孔中,如果是,則取消碰撞。 這些只是一些想法。 高溫超導

使用軸的邏輯:當X> targetX和X <targetX + width->確認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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM