这期内容当中小编将会给大家带来有关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; }}
上述就是小编为大家分享的Unity怎么实现已知落点和速度自动计算发射角度了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。