本文实例为大家分享了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; } }
实际效果
抛射效果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持鸟哥教程(niaoge.com)。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#niaoge.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。