现在的位置: 首页 > 综合 > 正文

【Unity3D自学记录】Unity3D显示NPC名称

2017年10月24日 ⁄ 综合 ⁄ 共 1136字 ⁄ 字号 评论关闭
[csharp] view
plain
copy

  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class NPCName : MonoBehaviour {  
  5.     //主角对象  
  6.     private GameObject player;  
  7.     //主摄像机对象  
  8.     private Camera camera;  
  9.     //NPC名称  
  10.     private string name = "我是NPC";  
  11.   
  12.     void Start()  
  13.     {  
  14.         //根据Tag得到主角对象  
  15.         player = GameObject.FindGameObjectWithTag("MainCamera");  
  16.         camera = Camera.main;  
  17.     }  
  18.   
  19.     void OnGUI()  
  20.     {  
  21.         //得到NPC头顶在3D世界中的坐标  
  22.         Vector3 worldPosition = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);  
  23.         //根据NPC头顶的3D坐标换算成它在2D屏幕中的坐标  
  24.         Vector2 position = camera.WorldToScreenPoint(worldPosition);  
  25.         //得到真实NPC头顶的2D坐标  
  26.         position = new Vector2(position.x, Screen.height - position.y);  
  27.         //计算NPC名称的宽高  
  28.         Vector2 nameSize = GUI.skin.label.CalcSize(new GUIContent(name));  
  29.         //设置显示颜色为黄色  
  30.         GUI.color = Color.red;  
  31.         //绘制NPC名称  
  32.         GUI.Label(new Rect(position.x - (nameSize.x / 2), position.y - nameSize.y, nameSize.x, nameSize.y), name);  
  33.   
  34.     }  
  35. }  

http://blog.csdn.net/daijinghui512/article/details/38398033

抱歉!评论已关闭.