欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

UGUI 虚拟摇杆

发布时间:2023/12/14 编程问答 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 UGUI 虚拟摇杆 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

目录

    • 简介
    • UGUI实现虚拟摇杆原理
    • 功能实现
    • 资源下载

简介

虚拟摇杆在手游中是重要组成部分,Unity的UGUI可很容易实现虚拟摇杆功能。大致分成三部分介绍。第一部分介绍如何通过UGUI实现虚拟摇杆功能。第二部分介绍如何通过虚拟摇杆控制物体移动和旋转。第三部分介绍如何用Entitas、Ecs框架结合JobSystem实现虚拟摇杆功能。

UGUI实现虚拟摇杆原理

  • 利用IBeginDragHandler,IDragHandler,IEndDragHandler接口实现对控件拖动事件的监听
  • 在OnDrag事件中利用函数RectTransformUtility.ScreenPointToLocalPointInRectangle设置拖拽位置

功能实现

  • 布局(最外层为panel,JoyStick为背景图片,Handle_Ridged为中间圆盘)
  • 代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using System;[RequireComponent(typeof(RectTransform))] public class JoyStickHandle : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler{public event Action OnBeginDragEvent = delegate { }; public event Action<Vector2> OnDragEvent = delegate(Vector2 vector2) { };public event Action OnEndDragEvent = delegate { };public RectTransform rtJoyStick;private Transform tfHandle;private float radius = 0f;private float limit = 0f;private Vector2 targetPos;public Vector2 TargetPos{get { return targetPos; }private set { }}// Use this for initializationvoid Start (){tfHandle = this.GetComponent<RectTransform>();radius = (rtJoyStick.rect.xMax - rtJoyStick.rect.xMin) / 2;limit = radius * radius;}public void OnBeginDrag(PointerEventData eventData){if (OnBeginDragEvent != null){OnBeginDragEvent();}}public void OnDrag(PointerEventData eventData){if (RectTransformUtility.ScreenPointToLocalPointInRectangle(rtJoyStick, eventData.position,eventData.pressEventCamera, out targetPos)){DealDragEvent();}}private void DealDragEvent(){if (targetPos.sqrMagnitude > limit){targetPos = targetPos.normalized * radius;}tfHandle.localPosition = targetPos;if (OnDragEvent != null){OnDragEvent(targetPos);}}public void OnEndDrag(PointerEventData eventData){tfHandle.localPosition = Vector3.zero;targetPos = Vector2.zero;if (OnEndDragEvent != null){OnEndDragEvent();}} }

资源下载

https://download.csdn.net/download/eie08027/10750360

总结

以上是生活随笔为你收集整理的UGUI 虚拟摇杆的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。