前几天做了一个实时指向目标的箭头的功能,现在把代码拿出来分享一下.
具体功能是当目标移动的时候,屏幕上有一个箭头会根据目标物体的移动改变位置和旋转角度,达到一直在屏幕上指向目标的 目的,不多上简单粗暴的上代码:
public Transform m_tArrow;//指向箭头
public Transform m_tTarget;//目标物体
public Transform m_tPlayer;//玩家
public Camera uiCam;//需要UGUI的Camera模式,这里要加入Camera
public RectTransform parent;//UGUI的画布
public int m_iDisFromPlayer;//距离中心点的距离
private Vector3 m_vArrowPoint;
private Vector3 m_vArrowScnPoint;
private Vector3 m_vPlayerScnPoint;
private Vector2 m_vArrowUIPoint;
private Vector2 m_vPlayerUIPoint;
void Update()
{
m_vArrowPoint = (m_tTarget.position - m_tPlayer.position).normalized * 5 + m_tPlayer.position;
m_vArrowScnPoint = Camera.main.WorldToScreenPoint(m_vArrowPoint);
m_vPlayerScnPoint = Camera.main.WorldToScreenPoint(m_tPlayer.position);
RectTransformUtility.ScreenPointToLocalPointInRectangle(parent, m_vArrowScnPoint, uiCam, out m_vArrowUIPoint);//通过这个函数测算箭头在屏幕上的位置
RectTransformUtility.ScreenPointToLocalPointInRectangle(parent, m_vPlayerScnPoint, uiCam, out m_vPlayerUIPoint);//通过这个函数测算玩家在屏幕上的位置
m_vArrowUIPoint = m_vPlayerUIPoint + (m_vArrowUIPoint - m_vPlayerUIPoint).normalized * m_iDisFromPlayer;//通过玩家在屏幕上的位置来修正箭头的位置
m_tArrow.localPosition = new Vector3(m_vArrowUIPoint.x, m_vArrowUIPoint.y, 0);//给箭头设置位置
UILookAt(m_tArrow, m_vArrowUIPoint - m_vPlayerUIPoint, Vector3.up);//给箭头设置方向
}
/// <summary>这个方法是让箭头指向处于屏幕中间的玩家坐标与箭头坐标向量的方向</summary>
/// <param name="ctrlObj">控制的箭头</param>
public void UILookAt(Transform ctrlObj, Vector3 dir, Vector3 lookAxis)
{
Quaternion q = Quaternion.identity;
q.SetFromToRotation(lookAxis, dir);
ctrlObj.eulerAngles = new Vector3(q.eulerAngles.x, 0, q.eulerAngles.z);
}
以下是这个脚本在Unity里面的设置说明