using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 导航UI控制类
/// </summary>
public class GuideUICtl : MonoBehaviour
{
public Transform m_target; //指向目标
public RectTransform m_arrow; //UI箭头
// Update is called once per frame
void Update() {
//控制导航UI箭头旋转
Vector3 euler = m_arrow.eulerAngles;
euler.z = GetGuideUIAngle();
m_arrow.eulerAngles = euler;
}
/// <summary>
/// 获得导航UI旋转角度
/// </summary>
/// <returns></returns>
private float GetGuideUIAngle() {
//脚本挂置在玩家上
//以玩家前方的单位向量为起始
Vector3 from = this.transform.forward;
//求出目标点与玩家之间的向量
Vector3 to = m_target.position - this.transform.position;
//求出两向量之间的叉乘
Vector3 cross = Vector3.Cross(from, to);
//求出两向量之间的角度
float angle = Vector3.Angle(from, to);
//根据叉乘求出带符号的角度
//cross.y > 0:目标向量位于起始向量右侧
//cross.y < 0:目标向量位于起始向量左侧
angle = cross.y > 0 ? -angle : angle;
return angle;
}
}
效果:
源程序:
链接:https://pan.baidu.com/s/1YCjimtROinf7yoXvzSCT0A
提取码:se2w