c#碰撞编程-动量
本文关键字:动量 编程 碰撞 | 更新日期: 2023-09-27 17:52:37
我正在编写一款3D XNA游戏,我正在努力理解如何在我的两个玩家之间执行类似动量的碰撞。从根本上来说,游戏的概念是让任何一名玩家击打另一名玩家并尝试将对手从关卡中击倒(就像《Smash Bros》游戏一样)以获得一分。
//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轴上向后推,现在很明显,这是行不通的,不是很直观,这就是我的问题所在,因为我一直在努力想出一个解决方案,我想要的是,当其中一个玩家与另一个玩家碰撞时,它们基本上会交换向量,从而产生我想要的弹跳效果,而不仅仅是影响一个轴,而是两个X轴。z .
感谢您花时间阅读,如果有人能想到任何解决方案,我将不胜感激。
指出:
基本上,在你想要做的碰撞中,你想要一个弹性碰撞,其中动能和动量都是守恒的。动量(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信息的原因是,如果你想要非正面碰撞或者不同质量的碰撞,你应该能够结合它。如果质量不一样,速度不会简单地改变大小和方向。会涉及到更多的数学问题。