Unity實現簡單虛擬搖桿
阿新 • • 發佈:2020-04-15
本文例項為大家分享了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; } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。