这篇文章主要讲解了unity实现虚拟摇杆控制Virtual Joystick的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。


using UnityEngine;
using UnityEngine.UI;
public class TouchJoystick : MonoBehaviour
{
public GameObject go;//需要通过虚拟摇杆控制的目标物体
public float moveSpeed = 3;//移动速度
public Image touchPoint;//摇杆轴对象
private Vector3 OriginalPos_TP;//摇杆轴的初始位置
private RectTransform rectTransform_TP;//摇杆轴的位置组件
private float radius;//摇杆轴移动的大半径
void Start()
{
radius = this.GetComponent().rect.width*0.5f;
rectTransform_TP = touchPoint.GetComponent();
OriginalPos_TP = rectTransform_TP.position;
}
void Update()
{
//第一次触摸屏幕时,整个虚拟摇杆的位置更新
if (Input.GetMouseButtonDown(0))
{
this.GetComponent().position = Input.mousePosition;
OriginalPos_TP = rectTransform_TP.position;
}
if (Input.GetMouseButton(0))
{
//取得触摸点与虚拟轴初始点的距离
float distance = Vector3.Distance(Input.mousePosition, OriginalPos_TP);
//取得一个初始轴点指向触摸点的向量
Vector3 pos = Input.mousePosition - OriginalPos_TP;
//如果距离大于可移动半径
if (distance > radius)
rectTransform_TP.position = OriginalPos_TP + pos.normalized*radius;//设置轴点到大半径位置
else
rectTransform_TP.position = Input.mousePosition;//否则轴点在当前触摸位置
//以(0,1,0)为参考点,计算单位轴向量与之夹角
float angle = Vector3.Angle(new Vector3(0, 1, 0), new Vector3(pos.normalized.x, pos.normalized.y, 0));
//移动物体
go.transform.Translate(new Vector3(0, 0, pos.normalized.magnitude*moveSpeed)*Time.deltaTime);
//更新控制物体的旋转与轴向方向一致
if (pos.normalized.x > 0)
go.transform.rotation = Quaternion.AngleAxis(angle, Vector3.up);
else
go.transform.rotation = Quaternion.AngleAxis(-angle, Vector3.up);
}
else
rectTransform_TP.position = OriginalPos_TP;//没有触摸时回到初始位置
}
} 另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。