實現效果:

實現:
使用NGUI添加虛擬搖桿背景和其子物體按鈕,為按鈕Attach boxcollider和ButtionScript。為按鈕添加如下腳本:
注意:其中的靜態屬性可以在控制物體移動的代碼中訪問用於控制。
1 using UnityEngine; 2 using System.Collections; 3 4 public class joyStickControl : MonoBehaviour { 5 6 public static float h=0; 7 public static float v = 0; 8 9 private float parentHeight; 10 private float parentWidth; 11 12 private bool isPress=false; 13 14 UISprite parentSpirite; 15 16 void Awake() 17 { 18 parentSpirite = transform.parent.GetComponent<UISprite>(); 19 parentWidth = parentSpirite.width; 20 parentHeight = parentSpirite.height; 21 } 22 23 24 // Update is called once per frame 25 void Update () { 26 27 if (isPress) 28 { 29 Vector2 touchpos = UICamera.lastTouchPosition; 30 31 touchpos -=new Vector2(parentWidth / 2, parentHeight / 2); 32 float distance = Vector2.Distance(touchpos, Vector2.zero); 33 if(distance<53) 34 { 35 transform.localPosition = touchpos; 36 } 37 else 38 { 39 transform.localPosition = touchpos.normalized * 53; 40 } 41 42 h = transform.localPosition.x / 53; 43 v = transform.localPosition.y / 53; 44 45 } 46 else 47 { 48 transform.localPosition = Vector2.zero; 49 h = 0; 50 v = 0; 51 } 52 53 } 54 55 void OnPress(bool isPress) 56 { 57 this.isPress = isPress; 58 } 59 }
控制物體移動的代碼:
注意:在使用虛擬搖桿的時候則忽略鍵盤控制的移動操作。
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 () { 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相一致。

Easy Touch 這個插件想必很多人都有所耳聞,可以迅速實現觸摸操作。很適合移動端游戲的觸摸輸入控制,支持觸摸,點擊,拖拽,兩指縮放。想要節省移動端游戲輸入開發的時間可以下載使用
