unity實(shí)現(xiàn)虛擬搖桿控制Virtual Joystick
更新時(shí)間:2020年04月15日 11:41:11 作者:代碼黑洞_
這篇文章主要為大家詳細(xì)介紹了unity實(shí)現(xiàn)虛擬搖桿控制Virtual Joystick,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了unity實(shí)現(xiàn)虛擬搖桿控的具體代碼,供大家參考,具體內(nèi)容如下
using UnityEngine; using UnityEngine.UI; public class TouchJoystick : MonoBehaviour { public GameObject go;//需要通過虛擬搖桿控制的目標(biāo)物體 public float moveSpeed = 3;//移動(dòng)速度 public Image touchPoint;//搖桿軸對(duì)象 private Vector3 OriginalPos_TP;//搖桿軸的初始位置 private RectTransform rectTransform_TP;//搖桿軸的位置組件 private float radius;//搖桿軸移動(dòng)的最大半徑 void Start() { radius = this.GetComponent<RectTransform>().rect.width*0.5f; rectTransform_TP = touchPoint.GetComponent<RectTransform>(); OriginalPos_TP = rectTransform_TP.position; } void Update() { //第一次觸摸屏幕時(shí),整個(gè)虛擬搖桿的位置更新 if (Input.GetMouseButtonDown(0)) { this.GetComponent<RectTransform>().position = Input.mousePosition; OriginalPos_TP = rectTransform_TP.position; } if (Input.GetMouseButton(0)) { //取得觸摸點(diǎn)與虛擬軸初始點(diǎn)的距離 float distance = Vector3.Distance(Input.mousePosition, OriginalPos_TP); //取得一個(gè)初始軸點(diǎn)指向觸摸點(diǎn)的向量 Vector3 pos = Input.mousePosition - OriginalPos_TP; //如果距離大于可移動(dòng)半徑 if (distance > radius) rectTransform_TP.position = OriginalPos_TP + pos.normalized*radius;//設(shè)置軸點(diǎn)到最大半徑位置 else rectTransform_TP.position = Input.mousePosition;//否則軸點(diǎn)在當(dāng)前觸摸位置 //以(0,1,0)為參考點(diǎn),計(jì)算單位軸向量與之夾角 float angle = Vector3.Angle(new Vector3(0, 1, 0), new Vector3(pos.normalized.x, pos.normalized.y, 0)); //移動(dòng)物體 go.transform.Translate(new Vector3(0, 0, pos.normalized.magnitude*moveSpeed)*Time.deltaTime); //更新控制物體的旋轉(zhuǎn)與軸向方向一致 if (pos.normalized.x > 0) go.transform.rotation = Quaternion.AngleAxis(angle, Vector3.up); else go.transform.rotation = Quaternion.AngleAxis(-angle, Vector3.up); } else rectTransform_TP.position = OriginalPos_TP;//沒有觸摸時(shí)回到初始位置 } }
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#跨平臺(tái)開發(fā)之使用C/C++生成的動(dòng)態(tài)鏈接庫
這篇文章介紹了C#跨平臺(tái)開發(fā)之使用C/C++生成的動(dòng)態(tài)鏈接庫,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-01-01c# 圓形識(shí)別方案和直線識(shí)別方案的參考示例
這篇文章主要介紹了c# 圓形識(shí)別方案和直線識(shí)別方案的實(shí)現(xiàn)示例,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03C#實(shí)現(xiàn)軟件開機(jī)自動(dòng)啟動(dòng)的兩種常用方法總結(jié)
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)軟件開機(jī)自動(dòng)啟動(dòng)的兩種常用方法,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以了解一下2023-07-07C#從windows剪貼板獲取并顯示文本內(nèi)容的方法
這篇文章主要介紹了C#從windows剪貼板獲取并顯示文本內(nèi)容的方法,涉及C#操作剪貼板的相關(guān)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04C#實(shí)現(xiàn)簡單屏幕監(jiān)控的方法
這篇文章主要介紹了C#實(shí)現(xiàn)簡單屏幕監(jiān)控的方法,涉及C#的圖標(biāo)隱藏及屏幕截圖等技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-04-04