关于unity:UGUI-自定义摇杆

自定义一个虚构摇杆,具体须要是:1、未点击时核心的小圆点暗藏 2、点击通明背景范畴内时操作栏挪动到点击地位 3、拖拽小圆点输入拖拽方向 4、松开时操作栏复位,小圆点暗藏
一、UI制作
1、创立一个Joystick的背景通明的Image,作为点击的范畴
2、创立Joystick下创立一个子物体TouchBg,作为操作栏
3、创立TouchBg下创立一个子物体TouchPoint

二、创立脚本Joystick附加在Joystick物体上,继承ScrollRect,将TouchPoint赋值给Content参数,将TouchBg赋值给ViewPort参数

三、编写Joystick脚本

/********************************************************************
    文件:Joystick.cs
    作者:Panngdudu
    日期:2020/12/19
    形容: 虚构摇杆性能
*********************************************************************/

using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class Joystick : ScrollRect, IPointerDownHandler, IPointerUpHandler, IDragHandler
{
    public GameObject touchBgGo;
    public GameObject touchPointGo;

    //事件触发的回调
    public Action<Vector2> onDragCallback;//拖拽事件的回调,参数1:方向

    protected float radius = 100;

    protected override void Start()
    {
        radius = touchPointGo.GetComponent<RectTransform>().sizeDelta.x * 0.7f;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        touchPointGo.SetActive(true);
        touchBgGo.transform.position = eventData.position;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        touchPointGo.SetActive(false);
        touchBgGo.transform.localPosition = Vector2.zero;
    }

    public void OnDrag(PointerEventData eventData)
    {
        base.OnDrag(eventData);
        var contentPos = this.content.anchoredPosition;
        if (contentPos.magnitude > radius)
        {
            contentPos = contentPos.normalized * radius;
            SetContentAnchoredPosition(contentPos);
        }

        onDragCallback?.Invoke(contentPos.normalized);
    }
}

gitee地址:https://gitee.com/pangdudu010…

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理