Unity兩個(gè)定點(diǎn)之間的拋物線運(yùn)動(dòng)

using UnityEngine;

using System.Collections;


public class parabola : MonoBehaviour {

    
public float ShotSpeed = 10; // 拋出的速度
    
private float time;          // A-B的時(shí)間
    
public Transform pointA;     // 起點(diǎn)
    
public Transform pointB;     // 終點(diǎn)
    
public float g = -10;        // 重力加速度

    
private Vector3 speed;       // 初速度向量
    
private Vector3 Gravity;             // 重力向量
    
private Vector3 currentAngle;// 當(dāng)前角度
    
void Start()
    {
        
  // 時(shí)間=距離/速度
        
  time = Vector3.Distance(pointA.position, pointB.position)/ShotSpeed;

        

  // 設(shè)置起始點(diǎn)位置為A
        
  transform.position = pointA.position;

        

  // 通過(guò)一個(gè)式子計(jì)算初速度
        
  speed = new Vector3((pointB.position.x - pointA.position.x) / time,
(pointB.position.y - pointA.position.y) / time - 0.5f * g * time, (pointB.position.z - pointA.position.z) / time);
        

  // 重力初始速度為0
        
  Gravity = Vector3.zero;
    
}
    
private float dTime = 0;
    
// Update is called once per frame
    
void FixedUpdate()
    {
        
// v=gt
        
Gravity.y = g * (dTime += Time.fixedDeltaTime);

        
//模擬位移
        
transform.position += (speed + Gravity) * Time.fixedDeltaTime;

        
// 弧度轉(zhuǎn)度:Mathf.Rad2Deg
        
currentAngle.x = -Mathf.Atan((speed.y + Gravity.y) / speed.z) * Mathf.Rad2Deg;

        
// 設(shè)置當(dāng)前角度
        
transform.eulerAngles = currentAngle;
    }
}


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容