Unity3D使用使用UGUI开发原生虚拟摇杆开发原生虚拟摇杆
主要为大家详细介绍了Unity3D使用UGUI开发原生虚拟摇杆,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的
小伙伴们可以参考一下
在Unity3d中开发虚拟摇杆方式有比较多,可以使用EasyTouch、FairyGUI等插件来开发。本文给大家介绍使用Unity3d的原生UGUI来开发出
自己的虚拟摇杆,这样可以减少游戏资源包的大小。
先展示下效果图:
现在开发我们的开发
创建一个Image1,并且在Image1创建一个子对象Image2
在Image1中挂载一个自定义脚本,这里我命名为Joystick
脚本代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Joystick : ScrollRect
{
private float mRadius;
public System.Action<RectTransform> JoystickMoveHandle;
public System.Action<RectTransform> JoystickEndHandle;
protected override void Start()
{
mRadius = this.GetComponent<RectTransform>().sizeDelta.x * 0.5f;
this.content.gameObject.SetActive(false);
}
public override void OnDrag(PointerEventData eventData)
{
base.OnDrag(eventData);
this.content.gameObject.SetActive(true);
//虚拟摇杆移动
var contentPostion = this.content.anchoredPosition;
if (contentPostion.magnitude > mRadius)
{
contentPostion = contentPostion.normalized * mRadius;
SetContentAnchoredPosition(contentPostion);
}
//旋转
if (content.anchoredPosition.y != 0)
{
content.eulerAngles = new Vector3(0, 0, Vector3.Angle(Vector3.right, content.anchoredPosition) * content.anchoredPosition.y / Mathf.Abs(content.anchoredPosition.y) - 90);
}
}
private void FixedUpdate()
{
if (this.content.gameObject.activeInHierarchy)
{
if (JoystickMoveHandle != null)
{
JoystickMoveHandle(this.content);
}
}
}
评论0