[英]Projectile Not Correctly Inheriting Parent Velocity (Unity3D)
我試圖從一個以非常高的速度移動的玩家發射射彈。 問題是子彈似乎沒有繼承角速度。 如果玩家以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()移動播放器,但無法使用子彈產生任何結果
直接的問題是,在您創建和發射它之前,射彈不是物理模擬的一部分,這意味着玩家直到該點的旋轉將無法影響其移動。 我想如果你在開始時制造射彈,用弱關節將它連接到槍上,然后打開關節並在它被射擊時增加它的速度,這可能會起作用 - 但如果你只是“偽造”它真的會更簡單它。
這類似於您在物理教科書中找到的經典圓周運動示例。 當你的子彈圍繞玩家(槍內)圍成一圈時,其正常路徑(如果被釋放)將與玩家周圍的圓形路徑相切。 因此,當子彈被發射(並因此從圓形路徑釋放)時,玩家的角速度將轉換為子彈的線速度。 這是一個簡單的圖表,我把它放在一起,表示一個球在一個字符串上的情況,旋轉成一個圓圈:
你不希望在射彈發射后對射彈施加任何角速度 - 如你所見,這只會使射彈在自己的軸上旋轉。 相反,您想要向射彈施加額外的速度矢量,該射彈與玩家的旋轉相切(並且垂直於子彈的面部)。 那我們該怎么做呢?
那么,根據這個網站 ,在一個圓圈中旋轉的東西的任何一點的切向速度公式是:
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;
}
希望這可以幫助! 當你使用游戲物理時,閱讀一些基本的運動學/力學從來都不是一個壞主意,因為有時候依賴游戲物理實際上比設計你自己的解決方案更復雜。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.