Unity实现简单虚拟摇杆
更新时间:2020年04月14日 11:00:04 作者:ancoloo
这篇文章主要为大家详细介绍了Unity实现简单虚拟摇杆,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Unity虚拟摇杆的简单实现代码,供大家参考,具体内容如下
简单的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;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
C#中Hashtable与Dictionary的用法对比及选择
这篇文章主要介绍了C#中Hashtable与Dictionary的用法对比及选择方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2025-03-03
C# 9.0新特性——扩展方法GetEnumerator支持foreach循环
这篇文章主要介绍了C# 9.0新特性——扩展方法GetEnumerator支持foreach循环的相关资料,帮助大家更好的理解和学习c# 9.0,感兴趣的朋友可以了解下2020-11-11


最新评论