码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-08-06 11:57:01      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:unity3d

using UnityEngine;
using System.Collections;

public class NPCName : MonoBehaviour {
    //主角对象
    private GameObject player;
    //主摄像机对象
    private Camera camera;
    //NPC名称
    private string name = "我是NPC";

    void Start()
    {
        //根据Tag得到主角对象
        player = GameObject.FindGameObjectWithTag("MainCamera");
        camera = Camera.main;
    }

    void OnGUI()
    {
        //得到NPC头顶在3D世界中的坐标
        Vector3 worldPosition = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);
        //根据NPC头顶的3D坐标换算成它在2D屏幕中的坐标
        Vector2 position = camera.WorldToScreenPoint(worldPosition);
        //得到真实NPC头顶的2D坐标
        position = new Vector2(position.x, Screen.height - position.y);
        //计算NPC名称的宽高
        Vector2 nameSize = GUI.skin.label.CalcSize(new GUIContent(name));
        //设置显示颜色为黄色
        GUI.color = Color.red;
        //绘制NPC名称
        GUI.Label(new Rect(position.x - (nameSize.x / 2), position.y - nameSize.y, nameSize.x, nameSize.y), name);

    }
}


bubuko.com,布布扣

【Unity3D自学记录】Unity3D显示NPC名称,布布扣,bubuko.com

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

标签:unity3d

原文地址:http://blog.csdn.net/daijinghui512/article/details/38398033

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!