Unity3d 基於NGUI的虛擬搖桿實現
阿新 • • 發佈:2019-01-01
實現效果預覽
C#程式碼
實現:
使用NGUI新增虛擬搖桿背景和其子物體按鈕,為按鈕Attach boxcollider和ButtionScript。為按鈕新增如下指令碼:
注意:其中的靜態屬性可以在控制物體移動的程式碼中訪問用於控制。
using UnityEngine;
using System.Collections;
public class joyStickControl : MonoBehaviour {
public static float h=0;
public static float v = 0;
private float parentHeight;
private float parentWidth;
private bool isPress=false;
UISprite parentSpirite;
void Awake()
{
parentSpirite = transform.parent.GetComponent<UISprite>();
parentWidth = parentSpirite.width;
parentHeight = parentSpirite.height;
}
// Update is called once per frame
void Update () {
// 觸控按下
if (isPress)
{
Vector2 touchpos = UICamera.lastTouchPosition;
// 預設情況下,座標原點位於父精靈左下角,下面的程式碼是調整原點到父物體中心
touchpos -=new Vector2(parentWidth / 2, parentHeight / 2);
// 計算原點和觸控點的距離
float distance = Vector2.Distance(touchpos, Vector2.zero);
if (distance<53)// 距離在父精靈背景中圓內,53為其半徑
{
transform.localPosition = touchpos;
}
else
{// 觸控點到原點的距離超過半徑,則把子精靈按鈕的位置設定為在父精靈背景的圓上,即控制搖桿只能在父精靈圓內移動
transform.localPosition = touchpos.normalized * 53;
}
// h和v返回[-1, 1]的數字,分別為水平和豎直方向
h = transform.localPosition.x / 53;
v = transform.localPosition.y / 53;
}
else
{// 觸控擡起,那麼把按鈕位置恢復到原點
transform.localPosition = Vector2.zero;
h = 0;v = 0;
}
}
// 觸控按下,isPress為true;擡起為false
void OnPress(bool isPress)
{ // 儲存標誌位:按下或擡起,用於在Update方法中判斷觸控是否按下
this.isPress = isPress;
}
}
控制物體移動的程式碼:
注意:在使用虛擬搖桿的時候則忽略鍵盤控制的移動操作。
using UnityEngine;
using System.Collections;
public class MoveCtroller : MonoBehaviour {
private float speed = 3;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
// 得到鍵盤上的水平和豎直方向,wasd和上下左右鍵
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
// 優先使用搖桿控制角色移動
if (joyStickControl.h!=0||joyStickControl.v!=0)
{
h = joyStickControl.h;
v = joyStickControl.v;
}
if (Mathf.Abs(h)>0.3||Mathf.Abs(v)>0.3)
{
GetComponent<CharacterController>().SimpleMove(new Vector3(h * speed, 0, v * speed));
}
}
}
注意: normalized的屬性獲取當前向量的方向向量,在這裡transform.localPosition = touchpos.normalized * 53; 用於使按鈕保持在虛擬搖桿背景圓的範圍類。
touchpos -=new Vector2(parentWidth / 2, parentHeight / 2);則是為了將觸點位置與中心按鈕的localpositon相一致。