弹丸未正确继承父级速度 (Unity3D)

Projectile Not Correctly Inheriting Parent Velocity (Unity3D)

我正在尝试从高速移动的玩家那里发射射弹。问题是子弹似乎没有继承 angular 速度。如果玩家以 500 U/s 的速度沿直线移动,则子弹会正确地继承该速度并将自己的速度加到该速度上:

GameObject bullet = Instantiate(projectile, gun.transform.position, gun.transform.rotation);
bullet.GetComponent<Rigidbody>().velocity = r.velocity + bullet.transform.forward *bulletSpeed;

但是,如果播放器转得非常快,它不会继承旋转速度,子弹看起来像是偏向一边。

我该如何实施?我尝试将玩家的 angular 速度分配给子弹,但这只会导致子弹在同一方向移动时旋转。

一些额外的细节:

眼前的问题是,直到您创建并发射弹射物时,弹射物才成为物理模拟的一部分,这意味着玩家在该点之前的旋转将无法影响它的运动。我想如果你在一开始就创建了射弹,将它连接到枪上的接头很弱,然后在发射时打破接头并增加它的速度,这可能会奏效 - 但如果你只是 "faked"它。

应用圆周运动

这类似于您在物理教科书中找到的经典圆周运动示例。当你的子弹绕着玩家(枪内)绕圈行进时,它的正常路径(如果释放)将与玩家周围的圆形路径相切。因此,当子弹被发射(并因此从圆形路径中释放)时,玩家的 angular 速度将转化为子弹的线速度。这是我放在一起的一个简单图表,表示球在绳子上旋转成一个圆圈的情况:

获取子弹的切向速度

您不想在射弹发射后对其施加任何类型的 angular 速度 - 如您所见,这只会使射弹沿其自身的轴旋转。相反,您想要对射弹应用一个额外的速度矢量,它与玩家的旋转相切(并且垂直于子弹的面)。那么我们该怎么做呢?

嗯,根据this website,旋转的物体上任意一点的切向速度公式为:

velocity = angularVelocity x radius

要记住的一个关键点是angular速度以弧度为单位,而不是度数。

所以,让我们把这些放在一起。以下是您如何编写此代码的一般思路:

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;
}

希望对您有所帮助!在处理游戏物理时,阅读一些基本的 kinematics/mechanics 从来都不是一个坏主意,因为有时依赖游戏物理实际上比仅仅设计自己的解决方案更复杂。