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;//需要通過(guò)虛擬搖桿控制的目標(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í)回到初始位置
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
淺談c#.net中巧用ToString()將日期轉(zhuǎn)成想要的格式
有時(shí)候我們要對(duì)時(shí)間進(jìn)行轉(zhuǎn)換,達(dá)到不同的顯示效果,更多的該怎么辦呢?2013-03-03
C#實(shí)現(xiàn)關(guān)機(jī)重啟及注銷實(shí)例代碼
這篇文章主要介紹了C#實(shí)現(xiàn)關(guān)機(jī)重啟及注銷實(shí)例代碼,適合新手參考學(xué)習(xí)之用,需要的朋友可以參考下2014-07-07
如何在Mac系統(tǒng)使用Visual Studio Code運(yùn)行Python
這篇文章主要介紹了Mac使用Visual Studio Code運(yùn)行Python環(huán)境的方法,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04
C#常用數(shù)據(jù)結(jié)構(gòu)和算法總結(jié)
這篇文章主要介紹了C#常用數(shù)據(jù)結(jié)構(gòu)和算法,這里我們總結(jié)了一些知識(shí)點(diǎn),可以幫助大家理解這些概念。2016-06-06
C#自定義函數(shù)NetxtString生成隨機(jī)字符串
這篇文章主要介紹了C#自定義函數(shù)NetxtString生成隨機(jī)字符串,是十分常見的重要功能,需要的朋友可以參考下2014-08-08

