一、用NGUI创建虚拟摇杆贴图

简单的虚拟摇杆控制移动(NGUI)-LMLPHP

先创建一个sprite作为背景叫做JoyStick 并添加一个BoxCollider,再创建一个sprite child作为虚拟摇杆中间的按钮,叫做button

二、通过虚拟摇杆获得x,y偏移值

 using UnityEngine;
using System.Collections; public class JoyStick : MonoBehaviour
{ private bool isPress = false;
private Transform button; //从虚拟摇杆的得到的x,y偏移值-1到1之间
public static float h = ;
public static float v = ;
void Awake()
{
button = transform.FindChild("button");
}
void OnPress(bool isPress)
{
this.isPress = isPress;
if (!isPress)
{
button.localPosition = Vector2.zero;
h = ;
v = ;
}
} void Update()
{
if (isPress)
{
Vector2 touchPos = UICamera.lastEventPosition - new Vector2(, );
float distance = Vector2.Distance(Vector2.zero, touchPos);
if (distance > )//虚拟摇杆按钮不能超过半径
{
touchPos = touchPos.normalized * ;
}
button.localPosition = touchPos; h = touchPos.x / ;
v = touchPos.y / ;
}
}
}

三、通过偏移控制移动 主角添加了character controller

 using UnityEngine;
using System.Collections; public class PlayerMove : MonoBehaviour
{
private CharacterController cc;
public float speed = 3f; void Awake()
{
cc = GetComponent<CharacterController>();
} // Update is called once per frame
void Update ()
{
//键盘控制
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical"); //虚拟摇杆控制
if (JoyStick.h != || JoyStick.v != )
{
h = JoyStick.h;
v = JoyStick.v;
} if (Mathf.Abs(h) > 0.1f || Mathf.Abs(v) > 0.1f)
{
Vector3 targetDir = new Vector3(h, , v);
transform.LookAt(targetDir + transform.position);
cc.SimpleMove(targetDir * speed);
} }
}
05-11 13:05