Unity实现已知落点和速度自动计算发射角度
程序员文章站
2023-11-18 18:08:22
本文实例为大家分享了unity已知落点和速度自动计算发射角度的具体代码,供大家参考,具体内容如下在发射物已知落点和速度的情况下如果刚体应用重力,不容易算出发射角度,以下为计算过程///
本文实例为大家分享了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; } }
实际效果
抛射效果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。