Unity3D:标签跟随功能

工程包下载:Unity3D虚拟现实开发之标签跟随功能

//这个是成品图,做的比较粗糙。不过重点在于功能的实现嘛


场景布置就不多说了,直接上脚本~

//move.cs
using UnityEngine;
using System.Collections;

public class move : MonoBehaviour {
	public float speed=8;
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	if (Input.GetKey ("w")) {
			transform.Translate(Vector3.forward*Time.deltaTime *speed);		
		}
	if (Input.GetKey ("s")) {
			transform.Translate(Vector3.back*Time.deltaTime *speed);		
		}
	if (Input.GetKey ("a")) {
			transform.Translate(Vector3.left*Time.deltaTime *speed);		
		}
	if (Input.GetKey ("d")) {
			transform.Translate(Vector3.right*Time.deltaTime *speed);		
		}
    
	}
}
1、这个是键盘控制代码,通过wsad控制中间的cube,即主要角色的移动。

2、通过声明public的speed,这样可以在unity 3D的inspector窗口实时调整数据,这种方式在实际调试中还是挺有用的。

//tag.cs
using UnityEngine;
using System.Collections;

public class tag : MonoBehaviour {
	
	//主摄像机对象
	public Camera worldcamera;         //世界相机
	//tag名称
	public string Name = "Character's name";
	//tag高度
	float tagHeight;	
	void Start ()
	{
		//得到摄像机对象
		worldcamera = Camera.main;

		<span style="color:#FF9900;"><span style="color:#000000;">//得到模型原始高度</span> </span>
		float size_y = transform.GetComponent<MeshFilter> ().mesh.bounds.size.y;  
		//得到模型缩放比例
		float scal_y = transform.localScale.y;
		//它们的乘积就是高度
		tagHeight = (size_y *scal_y) ;
		
	}
	
	void Update ()
	{
	}
	
	void OnGUI()
	{
		//得到tag在3D世界中的座标
		Vector3 worldPosition = new Vector3 (transform.position.x , transform.position.y +tagHeight,transform.position.z);
		//根据tag头顶的3D座标换算成它在2D屏幕中的座标
		Vector2 position = worldcamera.WorldToScreenPoint (worldPosition);
		//得到真实tag的2D座标
		position = new Vector2 (position.x, Screen.height - position.y);
		//计算tag的宽高
		Vector2 nameSize = GUI.skin.label.CalcSize (new GUIContent(Name));
		//设置显示颜色
		GUI.color  = Color.black;
		//绘制tag名称
		GUI.Label(new Rect(position.x - (nameSize.x/2),position.y - nameSize.y,nameSize.x,nameSize.y), Name);
		
	}

}
这个脚本的重点在于获取模型的高度,获取的方法有三种:

(1):为物体添加Collider,然后使用XXX.collider.bounds.size;该方法获得的size和缩放比例有关,是一一对应的,缩放比例一旦改变,size也改变。所以需要获取物体的scale:

float scal_y = transform.localScale.y;

然后与原始高度相乘即为实际高度。

(2):通过MeshFilter(网格过滤器)获取,该属组件的size属性可以获得对应的x,y,z方向的长度;这种方法size和缩放比例无关,缩放比例改变size不改变,size记录的是物体的原始尺寸。

  物体的各个方向缩放比例可以通过其transform的localScale来获得,即:XX.transform.localScale.x

  物体的实际尺寸=原始尺寸*缩放比例

  float xSize=XX.GetComponent().mesh.bounds.size.x*XX.transform.localScale.x;

(3)获得复杂物体的尺寸(诸如根节点没有MeshFilter,MeshRenderer组件,物体是由很多复杂不规则的小mesh子物体组成的)
如:

Camera的口径Size

当投影类型为Perspective时,fieldOfView属性表示口径的度数,范围为[1,179]

当投影类型为Orthgraphic,     orthographicSize属性为正交模式下的口径尺寸

最后将这两个脚本赋给主角对象就可以了


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章