標籤:
一、用NGUI建立虛擬搖杆貼圖
先建立一個sprite作為背景叫做JoyStick 並添加一個BoxCollider,再建立一個sprite child作為虛擬搖杆中間的按鈕,叫做button
二、通過虛擬搖杆獲得x,y位移值
1 using UnityEngine; 2 using System.Collections; 3 4 public class JoyStick : MonoBehaviour 5 { 6 7 private bool isPress = false; 8 private Transform button; 9 10 //從虛擬搖杆的得到的x,y位移值-1到1之間11 public static float h = 0;12 public static float v = 0;13 void Awake()14 {15 button = transform.FindChild("button");16 }17 void OnPress(bool isPress)18 {19 this.isPress = isPress;20 if (!isPress)21 {22 button.localPosition = Vector2.zero;23 h = 0;24 v = 0;25 }26 }27 28 void Update()29 {30 if (isPress)31 {32 Vector2 touchPos = UICamera.lastEventPosition - new Vector2(91, 91);33 float distance = Vector2.Distance(Vector2.zero, touchPos);34 if (distance > 73)//虛擬搖桿按鍵不能超過半徑35 {36 touchPos = touchPos.normalized * 73;37 } 38 button.localPosition = touchPos;39 40 h = touchPos.x / 73;41 v = touchPos.y / 73;42 }43 }44 }
三、通過位移控制移動 主角添加了character controller
1 using UnityEngine; 2 using System.Collections; 3 4 public class PlayerMove : MonoBehaviour 5 { 6 private CharacterController cc; 7 public float speed = 3f; 8 9 void Awake()10 {11 cc = GetComponent<CharacterController>();12 }13 14 // Update is called once per frame15 void Update () 16 {17 //鍵盤控制18 float h = Input.GetAxis("Horizontal");19 float v = Input.GetAxis("Vertical");20 21 //虛擬搖杆控制22 if (JoyStick.h != 0 || JoyStick.v != 0)23 {24 h = JoyStick.h;25 v = JoyStick.v;26 }27 28 if (Mathf.Abs(h) > 0.1f || Mathf.Abs(v) > 0.1f)29 {30 Vector3 targetDir = new Vector3(h, 0, v);31 transform.LookAt(targetDir + transform.position);32 cc.SimpleMove(targetDir * speed);33 }34 35 36 }37 }
簡單的虛擬搖杆控制移動(NGUI)