我正在尝试从高速移动的玩家那里发射射弹。问题是子弹似乎没有继承角速度。如果玩家以 500 U/s 的速度沿直线移动,则子弹会正确地继承该速度并将自己的速度加到该速度上:
GameObject bullet = Instantiate(projectile, gun.transform.position, gun.transform.rotation);
bullet.GetComponent<Rigidbody>().velocity = r.velocity + bullet.transform.forward *bulletSpeed;
但是,如果玩家转得非常快,它不会继承旋转速度,子弹看起来像是偏向一边。
我该如何实现?我尝试将玩家的角速度分配给子弹,但这只会导致子弹在沿同一方向移动时旋转。
一些额外的细节:
我正在使用 rigidbody.MoveRotation() 来旋转我的播放器,但我手动计算了 angularVelocity 以将其分配给子弹
我尝试使用 AddTorque() 移动播放器,但无法使用子弹产生任何结果
最佳答案
直接的问题是,在您创建和发射它之前,射弹不是物理模拟的一部分,这意味着玩家在那个点之前的旋转将无法影响它的运动。我想如果你在一开始就创建了射弹,用一个弱接头将它连接到枪上,然后在它被发射时打破接头并增加它的速度,这可能会起作用 - 但如果你只是“伪造”它真的会更简单
应用圆周运动
这类似于您在物理教科书中找到的经典圆周运动示例。当你的子弹绕着玩家(枪内)绕圈行进时,它的正常路径(如果释放)将与玩家周围的圆形路径相切。因此,当子弹被发射(并因此从圆形路径中释放)时,玩家的角速度将转化为子弹的线速度。这是我放在一起的一个简单图表,它表示球在绳子上绕圈旋转的情况:
获取子弹的切向速度
您不想在射弹发射后对其应用任何类型的角速度 - 如您所见,这只会使射弹沿其自身的轴旋转。相反,您想要对射弹应用一个额外的速度矢量,它与玩家的旋转相切(并且垂直于子弹的面)。那么我们该怎么做呢?
好吧,根据 this website , 做圆周运动的物体上任意一点的切向速度公式为:
velocity = angularVelocity x radius
要记住的一个关键点是 angularVelocity 的单位是弧度,而不是度数。
所以,让我们把这些放在一起。以下是您可能如何对此进行编码的一般思路:
FireGun() {
// Assumes the current class has access to the rotation rate of the player
float bulletAngularVelocityRad = Mathf.Deg2Rad(rotationRateDegrees)
// The radius of the circular motion is the distance between the bullet
// spawn point and the player's axis of rotation
float bulletRotationRadius =
(r.transform.position - gun.transform.position).magnitude;
GameObject bullet =
Instantiate(projectile, gun.transform.position, gun.transform.rotation);
// You may need to reverse the sign here, since bullet.transform.right
// may be opposite of the rotation
Vector3 bulletTangentialVelocity =
bulletAngularVelocityRad * bulletRotationRadius * bullet.transform.right;
// Now we can just add on bulletTangentialVelocity as a component
// vector to the velocity
bullet.GetComponent<Rigidbody>().velocity =
r.velocity + bullet.transform.forward * bulletSpeed + bulletTangentialVelocity;
}
希望对您有所帮助!在处理游戏物理时,阅读一些基本的运动学/力学从来都不是一个坏主意,因为有时依赖游戏物理实际上比仅仅设计自己的解决方案更复杂。
关于c# - 弹丸未正确继承父级速度 (Unity3D),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51879414/