Unity实现已知落点和速度自动计算发射角度

时间:2021-05-20

本文实例为大家分享了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; }}

实际效果

抛射效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章