2014-03-24 26 views
2

我正在編寫3D XNA遊戲,我正在努力理解如何實現我的兩個玩家之間的動量衝突。基本上這個概念是讓任何一個玩家都擊中另一個並試圖將對手擊倒關卡(比如粉碎兄弟遊戲)來得分。C#碰撞編程 - 動量

//Declared Variables 
    PrimitiveObject player1body; 
    PrimitiveObject player2body; 
    Vector3 player1vel = Vector3.Zero; 
    Vector3 player2vel = Vector3.Zero; 

    //Created in LoadContent() 
    PrimitiveSphere player1 = new PrimitiveSphere(tgd, 70, 32); 
    this.player1vel = new Vector3(0, 135, -120); 

    this.player1body = new PrimitiveObject(player1); 
    this.player1body.Translation = player1vel; 
    this.player1body.Colour = Color.Blue; 

    PrimitiveSphere player2 = new PrimitiveSphere(tgd, 70, 32); 
    this.player2vel = new Vector3(0, 135, 120); 

    this.player2body = new PrimitiveObject(player2); 
    this.player2body.Translation = player2vel; 
    this.player2body.Colour = Color.Red; 

    //Update method code for collision 
    this.player1vel.X = 0; 
    this.player1vel.Y = 0; 
    this.player1vel.Z = 0; 

    this.player2vel.X = 0; 
    this.player2vel.Y = 0; 
    this.player2vel.Z = 0; 

    if (player1body.BoundingSphere.Intersects(player2body.BoundingSphere)) 
    { 
     this.player2vel.Z += 10; 
    } 

正如你可以看到我做的是檢查PLAYER1的邊界球,當它與玩家2的那麼球員相交2將被推回在Z軸上,現在顯然這只是不會工作,並不是非常直觀,而我的問題就在於我試圖弄清楚如何提出解決方案,我想要發生的是當任何一個玩家與另一個玩家發生碰撞時,他們基本上會交換向量,讓它產生反彈效果I我正在尋找並且不僅僅影響一個座標軸,而是兩個座標軸X & Z.

感謝您抽出時間閱讀,我會感謝任何人都能想到的解決方案。

備註: PrimitiveSphere如果您想知道是使用(圖形設備,球體的直徑,tesselation)。

回答

1

基本上,在碰撞中,就像你正在試圖做的那樣,你需要一個彈性碰撞,其中動能和動量都被守恆。所有動量(P)是質量*速度,而動能(K)是1/2 *質量*速度^ 2。在你的情況下,我假設一切都有相同的質量。如果是這樣,K = 1/2 * v^2。所以,Kf = Ki和Pf = Pi。使用動能,玩家的速度量級被交換。只要碰撞正在進行(根據你的代碼,我認爲你很好),玩家將交換方向。

所以你可以做這樣簡單的東西:

if (player1body.BoundingSphere.Intersects(player2body.BoundingSphere)) 
{ 
    Vector3 p1v = this.player1vel; 
    this.player1vel = this.player2vel; 
    this.player2vel = p1v; 
} 

這應該創建一個相當現實的碰撞。現在我把P和K的相關信息包含進去,所以如果你不想碰到碰撞或者不同的羣衆,你應該可以加入這個信息。如果質量不一樣,速度不會簡單地改變幅度和方向。將涉及更多的數學。我希望這有幫助。

+1

我想你的意思是'this.player2vel = p1v;' – SLuck49

+0

感謝你提供的信息,這真的很有用,我會在稍後將這個信息應用到爆炸中,但不幸的是,當玩家現在應該碰撞時,其他與您的解決方案,這是奇怪的,因爲我看到它應該如何工作。 – Kyle

+0

@ShawnHolzworth,謝謝你,我做到了。 – davidsbro