UGUI实现的虚拟摇杆,可改变摇杆位置

时间:2022-02-25 13:26:50

实现方式主要参考这篇文章:http://www.cnblogs.com/plateFace/p/4687896.html。

主要代码如下:

 using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems; public delegate void JoystickMoveDelegate(JoystickData data); public class Joystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{ public GameObject joystickUI; //摇杆整体UI,方便Active
public RectTransform joystickCenter; //摇杆重心
public RectTransform joystickBackground; //摇杆背景 public RectTransform joystickRect;
private float radius;
bool isClick;
Vector2 clickPosition; public static event JoystickMoveDelegate JoystickMoveEvent; // Use this for initialization
void Start()
{
radius = ;
} // Update is called once per frame
void Update()
{
JoystickController();
} public void JoystickController()
{
if (isClick)
{
clickPosition = GetClickPosition();
float distance = Vector2.Distance(new Vector2(clickPosition.x, clickPosition.y) / Screen.width * , joystickRect.anchoredPosition); if (distance < radius)
{
//当距离小于半径就开始移动 摇杆重心
joystickCenter.anchoredPosition = new Vector2(clickPosition.x / Screen.width * - joystickRect.anchoredPosition.x, clickPosition.y / Screen.width * - joystickRect.anchoredPosition.y);
}
else
{
//求圆上的一点:(目标点-原点) * 半径/原点到目标点的距离
Vector2 endPosition = (new Vector2(clickPosition.x, clickPosition.y) / Screen.width * - joystickRect.anchoredPosition) * radius / distance;
joystickCenter.anchoredPosition = endPosition;
} if (JoystickMoveEvent != null)
{
JoystickMoveEvent(new JoystickData() { x = joystickCenter.anchoredPosition.x - joystickBackground.anchoredPosition.x, y = joystickCenter.anchoredPosition.y - joystickBackground.anchoredPosition.y });
} }
} public void OnPointerDown(PointerEventData eventData)
{
ChangeAlpha();
clickPosition = GetClickPosition();
joystickRect.anchoredPosition = clickPosition / Screen.width * ;
isClick = true;
} public void OnPointerUp(PointerEventData eventData)
{
ChangeAlpha(0.3f);
joystickCenter.anchoredPosition = Vector2.zero;
isClick = false;
} /// <summary>
/// 根据平台不同获取点击位置坐标
/// </summary>
/// <returns></returns>
Vector2 GetClickPosition()
{
if (Application.platform == RuntimePlatform.Android)
{
return Input.GetTouch().position; }
else if (Application.platform == RuntimePlatform.WindowsEditor)
{
return Input.mousePosition;
}
return Vector2.zero;
} /// <summary>
/// 改变图片alpha值
/// </summary>
/// <param name="alphaValue"></param>
void ChangeAlpha(float alphaValue)
{
joystickBackground.GetComponent<RawImage>().color = new Color(,,,alphaValue);
joystickCenter.GetComponent<Image>().color = new Color(, , , alphaValue);
}
} public class JoystickData
{
public float x;
public float y; }

主要实现了两个接口:IPointerDownHandler, IPointerUpHandler,监测按下和抬起事件。