這是在Unity中布局好的界面 通過左下的遙感控制中間的立方體的移動(dòng)
在中間的image中添加組件Event Trigger,并且將腳本掛載到中間的image上,在組件Event Trigger中添加兩個(gè)事件,Drag和EndDrag;
這兩個(gè)事件分別是在拖動(dòng)過程中調(diào)用,和拖動(dòng)結(jié)束后調(diào)用
using UnityEngine;
using System.Collections;using?
UnityEngine.UI;
public class YanganTest :?MonoBehaviour
{? ??
Vector3 _selfStartPos;? ??
RectTransform _CurrPos;? ??
float radius = 100f;? ??
GameObject Player;? ? ? ??
void Start()? ??
{? ? ? ??
_CurrPos = transform.GetComponent<RectTransform>();? ? ? ? //獲取當(dāng)前的RectTransform
_selfStartPos = transform.position; ? ? ? ?//獲取初始位置
GameObject PlayerP = Resources.Load("Cube") as GameObject; ?//獲取預(yù)設(shè)體 ? ? ?
Player = Instantiate(PlayerP, Vector3.zero, Quaternion.identity) as GameObject; ? ? ? ?//將預(yù)設(shè)體創(chuàng)建到場景中
Player.AddComponent<CharacterController>();? //為預(yù)設(shè)體添加CharacterController組件使其夠更加方便的控制
}? ??
public void Drag() ? ?//該方法在拖動(dòng)時(shí)調(diào)用,方法名并沒有規(guī)定
{? ? ? ??
if (Vector3.Distance(Input.mousePosition, _selfStartPos) <= radius) //如果鼠標(biāo)距離初始位置小于半徑 ? ? ??
{? ? ? ? ? ?
?transform.position = Input.mousePosition; ? ? ? ?//使中間的image的位置等于鼠標(biāo)位置
}? ??
}? ?
public void EndDrag()? ? //該方法在拖動(dòng)結(jié)束后調(diào)用,方法名并沒有規(guī)定
{? ? ? ?
?transform.position = _selfStartPos; ? //拖動(dòng)結(jié)束后使其歸位
?}? ??
public void FixedUpdate()? ? //執(zhí)行物理變化的函數(shù),每一幀執(zhí)行
{? ? ? ?
?if (Vector3.Distance(_CurrPos.position, _selfStartPos) >0) ? ? ? //當(dāng)中間的image被拖離初始位置時(shí)
?{? ? ? ? ? ??
float x = (Input.mousePosition - _selfStartPos).x; ? ? ? ? ? ?//獲取x坐標(biāo)
float y = (Input.mousePosition - _selfStartPos).y; ? ? ? ? ? ?//獲取y坐標(biāo)
Vector3 dir = new Vector3(x, 0,y); ? ? ? ? ? ? ? ? ? ? ? ?//初始化方向
Player.GetComponent<CharacterController>().SimpleMove(dir * 5 *Time.deltaTime);//獲取Player上的CharacterController組件,調(diào)用其中方法SimpleMove,這個(gè)方法的參數(shù)是一個(gè)三維向量,其中5是速度
}
}
}