Unity实现已知落点和速度自动计算发射角度
本文实例为大家分享了Unity已知落点和速度自动计算发射角度的具体代码,供大家参考,具体内容如下
创新互联是一家专注于做网站、成都网站建设与策划设计,马村网站建设哪家好?创新互联做网站,专注于网站建设10余年,网设计领域的专业建站公司;建站业务涵盖:马村等地区。马村做网站价格咨询:028-86922220
在发射物已知落点和速度的情况下如果刚体应用重力,不容易算出发射角度,以下为计算过程
////// 挂载到发射器上即可 /// 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().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); } } /// /// 执行整体旋转 /// /// 旋转的物体(自身) /// 目标点(鼠标指向) 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); } ////// 自动计算x欧拉角,即仰角 /// /// 目标点坐标 ///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实现已知落点和速度自动计算发射角度
链接地址:http://pwwzsj.com/article/pdsshd.html