首页 > 其他分享 >简写摇杆

简写摇杆

时间:2023-02-14 13:55:20浏览次数:33  
标签:Vector2 摇杆 backGround rock using 简写 public

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
/// <summary>
/// 写的是一个摇杆的代码
/// 步骤和使用
/// 1.因为代码使用了锚点坐标 所以要调节锚点 (使用的是固定为有下角)
/// 2.代码是要挂在摇杆后面哪个背景图上的
/// 3.背景图要直接在canvas下,不能在他上面套其他的东西,空对象也不行
/// </summary>
public class Rocker : MonoBehaviour,IDragHandler,IEndDragHandler
{
//鼠标拖拽遥感的偏移值 (偏移值是一个静态变量 可供外部获取,做移动等需求)
public static Vector2 offset;
//摇杆后的一个图片 和 摇杆
RectTransform backGround, rock;
//半径 (可拖拽的距离范围)
float r;
void Start()
{
rock = transform.Find("rocker").GetComponent<RectTransform>();
backGround = GetComponent<RectTransform>();
//取宽高比较小的一个作为可拖拽的圆半径范围
r = backGround.rect.width < backGround.rect.height ? backGround.rect.width / 2 : backGround.rect.height / 2;
}

public void OnDrag(PointerEventData eventData)
{
//一个v2上的距离
Vector2 pos = eventData.position - backGround.anchoredPosition;
//设置摇杆的位置
rock.anchoredPosition = Vector2.ClampMagnitude(pos, r);
//偏移值的计算
offset = rock.anchoredPosition / r;
}
public void OnEndDrag(PointerEventData eventData)
{
//清除摇杆的位置
rock.anchoredPosition = Vector2.zero;
//清除偏移值
offset = Vector2.zero;
}

}

 

-------------------------------------------------------------------------------------------------------

 

标签:Vector2,摇杆,backGround,rock,using,简写,public
From: https://www.cnblogs.com/zanzz/p/17119314.html

相关文章