一、用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 frame 15 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 }