您的位置:首页 > 移动开发 > Unity3D

Unity3D导弹追踪目标(三维效果)

2017-09-15 16:04 330 查看
网上搜到的大多是用Quaternion.LookRotation(),不知道为什么完全打不准目标(也许是因为要用在2D?),懒人已经哭晕在厕所,为了完成目标,不得不自己写(苦逼),此记结思路和结果。 主要追踪过程在update里面。

下图为最基本的效果,实际上飞机可以运行,导弹可以进行追踪,由于gif制作不熟练,只体现基本效果。

飞机模型和导弹模型都不属于我,属于我的只有代码。



导弹追踪移动目标

追踪理论(导弹的姿态)

使用球坐标进行定位,使用z轴的旋转角度表示俯仰角,y轴的旋转角度表示在xz平面的方位角。根据目标与导弹的位置调整导弹的姿态。

以下为代码:

using UnityEngine;
using System.Collections;

public class missile3 : MonoBehaviour {

public GameObject target;
public GameObject missile;
// Use this for initialization

private const float Max_Rotation = 180;
private static float Max_Rotation_frame = Max_Rotation / ((float)(Application.targetFrameRate == -1 ? 60 : Application.targetFrameRate));//每帧最大转动角度。

void Start () {
target = GameObject.Find ("F-15E");
missile=GameObject.Find ("missile2");
}

// Update is called once per frame
void Update () {
float dx = target.transform.position.x - this.transform.position.x;
float dy = target.transform.position.y - this.transform.position.y;
float dz = target.transform.position.z - this.transform.position.z;//目标与导弹位置差

//y轴为
float rotationTheta = Mathf.Atan(dz/dx)*180/Mathf.PI;//在dx,dz的旋转角度
float dxz = Mathf.Sqrt(d
4000
z * dz + dx * dx);
float rotationPhi = Mathf.Atan(dy/dxz)*180/Mathf.PI;//俯仰角

if (dx < 0) {
rotationTheta = rotationTheta > 0 ? 360 - rotationTheta : -rotationTheta;
} else {
rotationTheta=180-rotationTheta;
}//在世界坐标中的,在xz平面的旋转.
rotationPhi = 90 - rotationPhi;//俯仰角

float originRotationY = MakeSureRightRotation (transform.eulerAngles.y);
float originRotationZ = MakeSureRightRotation (transform.eulerAngles.z);

float addRotationY = rotationTheta- originRotationY;
float addRotationZ = rotationPhi- originRotationZ;

addRotationZ= Mathf.Max (-Max_Rotation_frame, Mathf.Min (Max_Rotation_frame, addRotationZ));//每frame可旋转的角度
addRotationY= Mathf.Max (-Max_Rotation_frame, Mathf.Min (Max_Rotation_frame, addRotationY));

this.transform.eulerAngles = new Vector3 (0,MakeSureRightRotation(this.transform.eulerAngles.y + addRotationY), MakeSureRightRotation(this.transform.eulerAngles.z + addRotationZ));
this.transform.Translate (new Vector3 (0, 2.0f * Time.deltaTime, 0));//导弹运行方向,根据自身坐标的y轴运行.

}
//碰撞触发爆炸
void OnCollisionStay(Collision collision){
Debug.Log ("S");
GameObject boom = Resources.Load ("boom object") as GameObject;
Object.Instantiate (boom,this.transform.position,this.transform.rotation);
Destroy (this.gameObject);
Debug.Log ("E");
}
//确保导弹在0到360度之间.
private float MakeSureRightRotation(float rotation){
rotation += 360;
rotation %= 360;
return rotation;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: