标签:
Unity里实现人物头顶的名字牌、血条的实现,网上很多博客有提到过。这里结合自己在项目中的开发,简单总结几点。
宣雨松的热门博客里有提到过直接利用Unity自身的OnGUI()实现人物血条:http://www.xuanyusong.com/archives/1032 。
撇开血条进度条的更新,重点关注头顶物件位置的更新。简化之,实现人物头顶的名字牌的。
核心代码如下:
using UnityEngine;
using System.Collections;
public class Following : MonoBehaviour {
public Camera m_Camera = null;
public GameObject m_goFollowing = null;
public Vector3 m_vOffset;
void OnGUI()
{
Vector3 vPosScreen = m_Camera.WorldToScreenPoint(m_goFollowing.transform.position + m_vOffset);
GUI.Label(new Rect(vPosScreen.x, Screen.height - vPosScreen.y, 200, 80), "牧羊少年奇幻之旅");
}
public class Following : MonoBehaviour {
public GameObject m_goFollowing = null;
public float m_fOffset = 0;
void Update()
{
gameObject.transform.position = m_goFollowing.transform.position + new Vector3(0, m_fOffset, 0);
gameObject.transform.rotation = Camera.main.transform.rotation;
}
}using UnityEngine;
using System.Collections;
public class Following : MonoBehaviour {
public GameObject m_goFollowing = null;
public float m_fOffset = 0;
private Camera m_go3DCamera = null;
private Camera m_go2DCamera = null;
void Start()
{
m_go3DCamera = GameObject.FindWithTag("MainCamera").GetComponent<Camera>();
m_go2DCamera = GameObject.Find("UI Root").transform.FindChild("Camera").GetComponent<Camera>();
}
void Update () {
Vector3 vPos = TransPos(m_goFollowing.transform.position + new Vector3(0, m_fOffset, 0));
gameObject.transform.position = new Vector3(vPos.x, vPos.y, 0); //get proper z, z = 0.0f simply
gameObject.transform.rotation = m_go2DCamera.transform.rotation; //keep the same rotation with camera, so Parallel with camera
}
//Transform WorldPos in 3DCamera to new WorldPos in 2DCamera. They share the same ScreenPos
Vector3 TransPos(Vector3 worldpos)
{
if (m_go3DCamera == null || m_go2DCamera == null)
{
return Vector3.zero;
}
Vector3 screenPos = m_go3DCamera.WorldToScreenPoint(worldpos);
Vector3 newWorldPos = m_go2DCamera.ScreenToWorldPoint(screenPos);
return newWorldPos;
}
}
标签:
原文地址:http://blog.csdn.net/u010153703/article/details/46574347