软件编程
位置:首页>> 软件编程>> C#编程>> Unity实现简单虚拟摇杆

Unity实现简单虚拟摇杆

作者:ancoloo  发布时间:2023-08-04 17:33:09 

标签:Unity,虚拟摇杆

本文实例为大家分享了Unity虚拟摇杆的简单实现代码,供大家参考,具体内容如下

简单的Unity虚拟摇杆实现,有详细注释。

Game界面

Unity实现简单虚拟摇杆

Inspector界面

Unity实现简单虚拟摇杆

摇杆脚本


public class YaoGanCtrl : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public RectTransform diPan;
public RectTransform anNiu;
public Vector2 direction;
Vector2 startPos;
public float moveRange;

public void OnBeginDrag(PointerEventData eventData)
{
//获取中心按钮的初始位置
startPos = anNiu.position;
}

public void OnDrag(PointerEventData eventData)
{
//计算摇杆方向
Vector2 newDir = eventData.position - startPos;
//计算活动范围的半径
float r = Mathf.Clamp(newDir.magnitude, -moveRange, moveRange);
//获取摇杆的单位方向
direction = newDir.normalized;
//设置中心按钮位置
anNiu.position = startPos + direction * r;
}

public void OnEndDrag(PointerEventData eventData)
{
//重置中心按钮位置
anNiu.position = startPos;
//重置单位方向
direction = Vector2.zero;
}

}

来源:https://blog.csdn.net/qq354886391/article/details/86763419

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com