欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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)文章

最新評(píng)論