您好,登錄后才能下訂單哦!
本文實例為大家分享了Unity已知落點和速度自動計算發射角度的具體代碼,供大家參考,具體內容如下
在發射物已知落點和速度的情況下如果剛體應用重力,不容易算出發射角度,以下為計算過程
/// <summary> /// 掛載到發射器上即可 /// </summary> public class Rotate : MonoBehaviour { public GameObject prefab; //發射物 public float speed; //發射物速度 public bool 拋射 = false; //拋射:仰角 > 45°,否:仰角 < 45° Ray RayMouse; Vector3 direction; Quaternion rotation; void Update() { if (Input.GetMouseButtonDown(0)) { GameObject go = Instantiate(prefab, transform.position, transform.rotation); go.AddComponent<Rigidbody>().velocity = go.transform.forward * speed; } RaycastHit hit; RayMouse = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(RayMouse.origin, RayMouse.direction, out hit, Mathf.Infinity)) { RotateToMouseDirection(gameObject, hit.point); } } /// <summary> /// 執行整體旋轉 /// </summary> /// <param name="obj">旋轉的物體(自身)</param> /// <param name="destination">目標點(鼠標指向)</param> void RotateToMouseDirection(GameObject obj, Vector3 destination) { direction = destination - obj.transform.position; rotation = Quaternion.LookRotation(direction); Vector3 finalAngle = rotation.eulerAngles; float targetAng = Angle(destination); finalAngle = new Vector3(-targetAng, finalAngle.y, finalAngle.z);//注意正負 obj.transform.localRotation = Quaternion.Euler(finalAngle); } /// <summary> /// 自動計算x歐拉角,即仰角 /// </summary> /// <param name="target">目標點坐標</param> /// <returns></returns> float Angle(Vector3 target) { float angleX; float distX = Vector2.Distance(new Vector2(target.x, target.z), new Vector2(transform.position.x, transform.position.z)); float distY = target.y - transform.position.y; float posBase = (Physics.gravity.y * Mathf.Pow(distX, 2.0f)) / (2.0f * Mathf.Pow(speed, 2.0f)); float posX = distX / posBase; float posY = (Mathf.Pow(posX, 2.0f) / 4.0f) - ((posBase - distY) / posBase); if (posY >= 0.0f) { if (拋射) //字段 angleX = Mathf.Rad2Deg * Mathf.Atan(-posX / 2.0f + Mathf.Pow(posY, 0.5f)); else angleX = Mathf.Rad2Deg * Mathf.Atan(-posX / 2.0f - Mathf.Pow(posY, 0.5f)); } else { angleX = 45.0f; } return angleX; } }
實際效果
拋射效果
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。