Unity中如何創建搖桿/控制物體移動

實現功能:點擊一定範圍內的屏幕,以點擊點爲中心生成一個搖桿,移動搖桿可以控制物體的移動。

ui佈局比較簡單,

Limit-yaogan決定搖桿的活動範圍

yaoganDI大圈

yaogan小圈

 

搖桿腳本部分的:需要引用三個拖拽的接口,用來達到搖桿的效果。IPointerDownHandler,IDragHandler,IPointerUpHandler

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class YaoganMager : MonoBehaviour,IPointerDownHandler,IDragHandler,IPointerUpHandler
{
    public float r;     //半徑
    public Vector2 placeValue; //位置
    public float pull;//拉扯
    /// <summary>
    /// 點擊過程中兩種情況
    /// 1、推拽在大圈裏,直接獲取位置就可以了
    /// 2、拖拽小圈在大圈外,獲取方向標準化*半徑,再加上大圈的位置,就可以限定住小圈,最遠也是隻能超出半徑
    /// </summary>
    /// <param name="eventData"></param>
    public void OnDrag(PointerEventData eventData)
    {
        if (Vector2.Distance(eventData.position,transform.GetChild(0).position)<=r)
        {
            transform.GetChild(0).GetChild(0).position = eventData.position;
        }
        else
        {
            transform.GetChild(0).GetChild(0).position =transform.GetChild(0).position + Vector3.Normalize((Vector3)eventData.position - transform.GetChild(0).position) * r;
            Debug.Log(Vector3.Normalize((Vector3)eventData.position - transform.GetChild(0).position));
        }
        placeValue.y = transform.GetChild(0).GetChild(0).position.y / r;
        placeValue.x = transform.GetChild(0).GetChild(0).position.x / r;
        pull = Vector2.Distance(transform.GetChild(0).GetChild(0).position, transform.GetChild(0).position) / r;
    }
    //點擊遙感出現,設置位置
    public void OnPointerDown(PointerEventData eventData)
    {
        transform.GetChild(0).gameObject.SetActive(true);
        transform.GetChild(0).position = eventData.position;
    }
    //點擊遙感消失,重置位置
    public void OnPointerUp(PointerEventData eventData)
    {
        transform.GetChild(0).gameObject.SetActive(false);
        transform.GetChild(0).GetChild(0).localPosition = Vector2.zero;
        placeValue = Vector2.zero;
        pull = 0;
    }
}

與物體關聯:

我把原理說一下,比較簡單。通過搖桿的拖拽,可以獲得小圈相對於大圈的一個偏移量關於(x,y)的,,若你控制的是水平方向的你可以定義一個vector3來接收這個偏移量(x,0,y);把vector3當作物體的移動方向,就實現了遙感於物體之間的關聯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章