Unity虚拟摇杆 Unity实现简单虚拟摇杆

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Unity虚拟摇杆 Unity实现简单虚拟摇杆

ancoloo   2021-04-21 我要评论

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

Game界面

Inspector界面

摇杆脚本

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;
 }

}

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们