生活随笔
收集整理的這篇文章主要介紹了
UGUI 虚拟摇杆
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
目錄
- 簡介
- UGUI實(shí)現(xiàn)虛擬搖桿原理
- 功能實(shí)現(xiàn)
- 資源下載
簡介
虛擬搖桿在手游中是重要組成部分,Unity的UGUI可很容易實(shí)現(xiàn)虛擬搖桿功能。大致分成三部分介紹。第一部分介紹如何通過UGUI實(shí)現(xiàn)虛擬搖桿功能。第二部分介紹如何通過虛擬搖桿控制物體移動(dòng)和旋轉(zhuǎn)。第三部分介紹如何用Entitas、Ecs框架結(jié)合JobSystem實(shí)現(xiàn)虛擬搖桿功能。
UGUI實(shí)現(xiàn)虛擬搖桿原理
- 利用IBeginDragHandler,IDragHandler,IEndDragHandler接口實(shí)現(xiàn)對(duì)控件拖動(dòng)事件的監(jiān)聽
- 在OnDrag事件中利用函數(shù)RectTransformUtility.ScreenPointToLocalPointInRectangle設(shè)置拖拽位置
功能實(shí)現(xiàn)
- 布局(最外層為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 { }}void 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
總結(jié)
以上是生活随笔為你收集整理的UGUI 虚拟摇杆的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。