栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

unity实现虚拟摇杆控制Virtual Joystick

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

unity实现虚拟摇杆控制Virtual Joystick

本文实例为大家分享了unity实现虚拟摇杆控的具体代码,供大家参考,具体内容如下

using UnityEngine;
using UnityEngine.UI;
 
public class TouchJoystick : MonoBehaviour
{
 
  public GameObject go;//需要通过虚拟摇杆控制的目标物体
  public float moveSpeed = 3;//移动速度
 
  public Image touchPoint;//摇杆轴对象
 
  private Vector3 OriginalPos_TP;//摇杆轴的初始位置
  private RectTransform rectTransform_TP;//摇杆轴的位置组件
 
  private float radius;//摇杆轴移动的最大半径
 
  void Start()
  {
    radius = this.GetComponent().rect.width*0.5f;
    rectTransform_TP = touchPoint.GetComponent();
    OriginalPos_TP = rectTransform_TP.position;
  }
 
  void Update()
  {
    //第一次触摸屏幕时,整个虚拟摇杆的位置更新
    if (Input.GetMouseButtonDown(0))
    {
      this.GetComponent().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;//设置轴点到最大半径位置
      else
 rectTransform_TP.position = Input.mousePosition;//否则轴点在当前触摸位置
      
      //以(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);
      //更新控制物体的旋转与轴向方向一致
      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;//没有触摸时回到初始位置
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/122202.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号