摇杆和虚拟摇杆在手游中的应用非常多,在Unity中的实现方法或许有很多,以下是我在做项目的时候写的一个摇杆的控制器。我采用的是NGUI做的摇杆,UI界面用NGUI和UGUI因人而异。有好的方案也望在评论中回复~~0v0
using UnityEngine;
using System.Collections;
public class JoyStick : MonoBehaviour
{
private bool IsPress = false;
private Transform Button;
public static float h = 0;
public static float v = 0;
void Awake()
{
Button = transform.Find("button");
}
void OnPress(bool IsPress)
{
this.IsPress = IsPress;
if (IsPress == false)
{
Button.localPosition =Vector3.zero;//局部坐标中心位置
h = 0;
v = 0;
}
}
void Update()
{
if (IsPress)
{
Vector2 TouchPosition = UICamera.lastTouchPosition;//获取拖拽的位置
TouchPosition -= new Vector2(91, 91);
float Distance = Vector2.Distance(Vector2.zero, TouchPosition);//获取与原点的距离
if (Distance > 70)//先在控制面板得到摇杆局部坐标的最大距离
{
TouchPosition = TouchPosition.normalized * 70;//获取单位向量后进行操作
Button.localPosition = TouchPosition;//超过最大距离则限定在边缘
}
else
{
Button.localPosition = TouchPosition;//没有超出接线则为目前的拖拽点
}
h = TouchPosition.x / 70;//单位向量
v = TouchPosition.y / 70;
}
}
}