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屬性爲正交模式下的口徑尺寸

最後將這兩個腳本賦給主角對象就可以了


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