unity實現(xiàn)虛擬搖桿控制Virtual Joystick
更新時間:2020年04月15日 11:41:11 作者:代碼黑洞_
這篇文章主要為大家詳細介紹了unity實現(xiàn)虛擬搖桿控制Virtual Joystick,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了unity實現(xiàn)虛擬搖桿控的具體代碼,供大家參考,具體內(nèi)容如下

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

