我只是從物理學開始,所以我並不總是知道自己在做什麼。這是一個2D項目,但我使用像SphereCollider等3D物理對象..計算/預測方法
我有什麼:
protected virtual IEnumerator OnTriggerStay(Collider other) {
yield return new WaitForFixedUpdate();
if(other.attachedRigidbody) {
Vector3 offsetVector = this.transform.position - other.transform.position;
float distance = offsetVector.magnitude;
float gravityForce = (other.rigidbody.mass * mass)/Mathf.Pow(distance, 2);
// Clamp gravity.
if(gravityForce > 1.0F) {
gravityForce = 1.0F;
}
other.attachedRigidbody.constantForce.force = offsetVector.normalized * gravityForce;
}
}
有:通過重力空間
物體漂浮和互相影響是可控制的物體,玩家可以在該物體上點擊並拖動一條線離開物體,以便在相反的方向上爲其施加力(射擊)。
我想達到的目標:
球員應該看到的方式粗略的預測,同時瞄準。這意味着方式預測需要考慮當前速度,當玩家釋放鼠標按鈕時應用的力以及周圍物體的重力。
我迄今爲止嘗試:
出於測試目的,我只保存計算/預測陣列中的位置,並繪製OnDrawGizmos那些位置()。
我寫了一個方法,它返回稱爲computeGravityForPosition(Vector3位置)的某個位置的重力影響。
並且那我如何努力來計算位置:
private void drawWayPrediction() {
Vector3 pos = this.transform.position;
// The offsetVector for the shooting action.
Vector3 forceVector = pos - Camera.main.ScreenToWorldPoint(Input.mousePosition);
forceVector.z = 0.0F;
// The predicted momentum scaled up to increase the strength.
Vector3 force = (forceVector.normalized * forceVector.magnitude);
// 1. I guess that this is wrong, but don't know how to do it properly.
momentum = this.rigidbody.velocity + force;
for(int i = 0; i < predictionPoints.Length; i++) {
float t = i * Time.fixedDeltaTime;
momentum += computeGravityForPosition(pos);
pos += momentum * t * t;
predictionPoints[i] = pos;
}
}
在開始的時候,當對象只是慢慢接近對方看起來還好。第一槍後,預測是完全錯誤的。我想這是因爲代碼中的1.。只是增加速度的力量可能是可怕的錯誤。
非常感謝您的時間。
編輯:
我去掉看似unnessecary部分。
我仍然認爲在代碼中存在的主要問題是1.。我只是不知道如何將對象的當前運動(從我只知道當前速度,據我所知的統一物理引擎)與新創建的力混合起來:
Vector3 forceVector = pos - Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3 force =(forceVector.normalized * forceVector.magnitude);
根據質量和距離的不同,影響射擊體的空間有幾個物體。所以我不確定是否有簡單的方法來計算容易彈道的路徑。 通過改變TimeScale,我不會影響我的軌跡計算速度。我通過使用Debug.Log(Time.DeltaTime);檢查了這一點。保存陣列中的位置僅用於測試目的。稍後我可以將其更改爲僅計算每次更新呼叫一次的時間步長,這將足夠快。 – Wipster
我認爲同樣的邏輯適用。您可以考慮對象的其他影響。當然,就像你說的那樣,根據你的具體要求,它可能會變得醜陋。 – Alex