2014-03-24 28 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