工程包下載:Unity3D虛擬現實開發之角色拾取
//這個是成品圖
角色拾取的原理是:由攝像機與屏幕上鼠標點擊的位置確定一條射線,由此射線射向3D世界,最先和此射線相交的物體就是被選中的物體,然後對該物體的操控編寫對應的代碼即可。具體代碼如下:
#鼠標控制
#pragma strict
var flag : boolean=true ;//通過初始化flag賦給物體初始座標
function Start(){
}
function Update () {
if (Input.GetMouseButton (0)) {
//聲明一條由鼠標位置發出垂直於屏幕的射線
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit)){ //判斷此物理事件
if(hit.transform.root.transform==this.transform) {
flag=!flag;
} } }
if(flag){
this.transform.position=Vector3(0,0,2);
}
else if(!flag){
this.transform.position=Vector3(2,0,2);
}
}
下面是相關的說明:
1.關於Physics.Raycast:
根據Unity聖典的解釋:
Returns
bool - True when the ray intersects any collider, otherwise false.
當光線投射與任何碰撞器交叉時爲真,否則爲假。
Description描述
Casts a ray against all colliders in the scene.
在場景中投下可與所有碰撞器碰撞的一條光線。
因此,這裏要求角色必須是或者添加了碰撞器,否則
if (Physics.Raycast (ray, hit)){ //判斷此物理事件
if(hit.transform.root.transform==this.transform) {
flag=!flag;
這個語句不會按照預期執行,flag不會發生改變。
2.調整主攝影機的屬性,使視野顯示需要操作的角色。