Unity3D基于UGUI实现虚拟摇杆

虚拟摇杆在移动游戏开发中,是很常见的需求,今天我们在Unity中,使用UGUI来实现一个简单的虚拟摇杆功能。

1.打开Unity,新创建一个UIJoystick.cs脚本,代码如下:

using UnityEngine;
using UnityEngine.EventSystems;

public class UIJoystick : MonoBehaviour, IDragHandler, IEndDragHandler
{
  /// <summary>
 /// 被用户拖动的操纵杆
  /// </summary>
  public Transform target;

  /// <summary>
 /// 操纵杆可移动的最大半径
  /// </summary>
  public float radius = 50f;

  /// <summary>
 /// 当前操纵杆在2D空间的x,y位置
  /// 摇杆按钮的值【-1,1】之间
  /// </summary>
  public Vector2 position;

 //操纵杆的RectTransform组件
 private RectTransform thumb;

 void Start()
 {
 thumb = target.GetComponent<RectTransform>();
 }

  /// <summary>
 /// 当操纵杆被拖动时触发
  /// </summary>
  public void OnDrag(PointerEventData data)
 {
 //获取摇杆的RectTransform组件,以检测操纵杆是否在摇杆内移动
 RectTransform draggingPlane = transform as RectTransform;
 Vector3 mousePos;

 //检查拖动的位置是否在拖动rect内,
 //然后设置全局鼠标位置并将其分配给操纵杆
 if (RectTransformUtility.ScreenPointToWorldPointInRectangle (draggingPlane, data.position, data.pressEventCamera, out mousePos)) {
  thumb.position = mousePos;
 }

 //触摸向量的长度(大小)
 //计算操作杆的相对位置
 float length = target.localPosition.magnitude;

 //如果操纵杆超过了摇杆的范围,则将操纵杆设置为最大半径
 if (length > radius) {
  target.localPosition = Vector3.ClampMagnitude (target.localPosition, radius);
 }

 //在Inspector显示操纵杆位置
 position = target.localPosition;
 //将操纵杆相对位置映射到【-1,1】之间
 position = position / radius * Mathf.InverseLerp (radius, 2, 1);
 }
  /// <summary>
 /// 当操纵杆结束拖动时触发
  /// </summary>
  public void OnEndDrag(PointerEventData data)
 {
 //拖拽结束,将操纵杆恢复到默认位置
 position = Vector2.zero;
 target.position = transform.position;
 }
}

2.如图创建UGUI,所用资源可在网上自行下载。

效果图如下:

3.打包运行即可。这样一个简单的虚拟摇杆就实现了。

下面是对以上虚拟摇杆代码的扩展(ps:只是多了一些事件,便于其他脚本访问使用)废话不多说来代码了

using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

//
// Joystick component for controlling player movement and actions using Unity UI events.
// There can be multiple joysticks on the screen at the same time, implementing different callbacks.
//
public class UIJoystick : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
  ///
  /// Callback triggered when joystick starts moving by user input.
  ///
  public event Action onDragBegin;

  ///
  /// Callback triggered when joystick is moving or hold down.
  ///
  public event Action onDrag;

  ///
  /// Callback triggered when joystick input is being released.
  ///
  public event Action onDragEnd;

  ///
  /// The target object i.e. jostick thumb being dragged by the user.
  ///
  public Transform target;

  ///
  /// Maximum radius for the target object to be moved in distance from the center.
  ///
  public float radius = 50f;

  ///
  /// Current position of the target object on the x and y axis in 2D space.
  /// Values are calculated in the range of [-1, 1] translated to left/down right/up.
  ///
  public Vector2 position;

  //keeping track of current drag state
  private bool isDragging = false;

  //reference to thumb being dragged around
 private RectTransform thumb;

  //initialize variables
 void Start()
 {
 thumb = target.GetComponent();

 //in the editor, disable input received by joystick graphics:
    //we want them to be visible but not receive or block any input
 #if UNITY_EDITOR
  Graphic[] graphics = GetComponentsInChildren();
 // for(int i = 0; i < graphics.Length; i++)
 // graphics[i].raycastTarget = false;
 #endif
 }

  ///
  /// Event fired by UI Eventsystem on drag start.
  ///
  public void OnBeginDrag(PointerEventData data)
  {
    isDragging = true;
    if(onDragBegin != null)
      onDragBegin();
  }

  ///
  /// Event fired by UI Eventsystem on drag.
  ///
  public void OnDrag(PointerEventData data)
  {
    //get RectTransforms of involved components
    RectTransform draggingPlane = transform as RectTransform;
    Vector3 mousePos;

    //check whether the dragged position is inside the dragging rect,
    //then set global mouse position and assign it to the joystick thumb
    if (RectTransformUtility.ScreenPointToWorldPointInRectangle(draggingPlane, data.position, data.pressEventCamera, out mousePos))
    {
      thumb.position = mousePos;
    }

    //length of the touch vector (magnitude)
    //calculated from the relative position of the joystick thumb
    float length = target.localPosition.magnitude;

    //if the thumb leaves the joystick's boundaries,
    //clamp it to the max radius
    if (length > radius)
    {
      target.localPosition = Vector3.ClampMagnitude(target.localPosition, radius);
    }

    //set the Vector2 thumb position based on the actual sprite position
    position = target.localPosition;
    //smoothly lerps the Vector2 thumb position based on the old positions
    position = position / radius * Mathf.InverseLerp(radius, 2, 1);
  }

  //set joystick thumb position to drag position each frame
  void Update()
  {
    //in the editor the joystick position does not move, we have to simulate it
 //mirror player input to joystick position and calculate thumb position from that
 #if UNITY_EDITOR
  target.localPosition = position * radius;
  target.localPosition = Vector3.ClampMagnitude(target.localPosition, radius);
 #endif

    //check for actual drag state and fire callback. We are doing this in Update(),
    //not OnDrag, because OnDrag is only called when the joystick is moving. But we
    //actually want to keep moving the player even though the jostick is being hold down
    if(isDragging && onDrag != null)
      onDrag(position);
  }

  ///
  /// Event fired by UI Eventsystem on drag end.
  ///
  public void OnEndDrag(PointerEventData data)
  {
    //we aren't dragging anymore, reset to default position
    position = Vector2.zero;
    target.position = transform.position;

    //set dragging to false and fire callback
    isDragging = false;
    if (onDragEnd != null)
      onDragEnd();
  }
}

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

(0)

相关推荐

  • Unity实现简单虚拟摇杆

    本文实例为大家分享了Unity虚拟摇杆的简单实现代码,供大家参考,具体内容如下 简单的Unity虚拟摇杆实现,有详细注释. Game界面 Inspector界面 摇杆脚本 public class YaoGanCtrl : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { public RectTransform diPan; public RectTransform anNiu; public Vector2 d

  • Unity实现虚拟摇杆

    本文实例为大家分享了Unity实现虚拟摇杆的具体代码,供大家参考,具体内容如下 面板上设置一些属性,比如摇杆拖拽的距离,是否始终可视,是否限制虚拟摇杆位置(我是把虚拟摇杆限制在了屏幕的左下区域). 使用GetDirAndLength()方法去获得移动的方向和长度即可 using UnityEngine; /// <summary> /// 虚拟摇杆管理器 /// </summary> public class VirtualJoystickManager : MonoBehavio

  • Unity实现简单的虚拟摇杆

    本文实例为大家分享了Unity实现简单虚拟摇杆的具体代码,供大家参考,具体内容如下 需求:点击创建一个虚拟摇杆底盘,鼠标拖拽时候上方摇杆会跟随鼠标方向移动,并且不会超出摇杆盘范围 *摇杆功能另外实现 UI显示 using System.Collections; using System.Collections.Generic; using UnityEngine; public class RockingIcon : MonoBehaviour { public Transform touchP

  • Unity3D基于UGUI实现虚拟摇杆

    虚拟摇杆在移动游戏开发中,是很常见的需求,今天我们在Unity中,使用UGUI来实现一个简单的虚拟摇杆功能. 1.打开Unity,新创建一个UIJoystick.cs脚本,代码如下: using UnityEngine; using UnityEngine.EventSystems; public class UIJoystick : MonoBehaviour, IDragHandler, IEndDragHandler { /// <summary> /// 被用户拖动的操纵杆 /// &

  • Unity3D使用UGUI开发原生虚拟摇杆

    在Unity3d中开发虚拟摇杆方式有比较多,可以使用EasyTouch.FairyGUI等插件来开发.本文给大家介绍使用Unity3d的原生UGUI来开发出自己的虚拟摇杆,这样可以减少游戏资源包的大小. 先展示下效果图: 现在开发我们的开发 创建一个Image1,并且在Image1创建一个子对象Image2 在Image1中挂载一个自定义脚本,这里我命名为Joystick 脚本代码如下 using System.Collections; using System.Collections.Gene

  • 使用nginx配置基于域名的虚拟主机实现​

    1.什么是虚拟主机 虚拟主机使用特殊的技术,将一台运行的服务器,在逻辑上划分成多个主机.这样做主要是能让一台物理服务器上运行多个网站程序,这样就可以利用起来服务器剩余的空间.充分发挥服务器的作用.虚拟主机间,是完全独立的. 这样在使用nginx去搭建网站平台的时候,只需要使用一个nginx软件,就能运行多个基于ip或者基于域名的网站. 2.基于域名的虚拟主机 这种基于域名的虚拟主机是最常用的.基于ip的一般都是在内网中使用. (1)nginx.conf中的配置 只要在nginx.conf中添加上

  • Unity实现虚拟摇杆效果

    本文实例为大家分享了Unity实现虚拟摇杆效果的具体代码,供大家参考,具体内容如下 首先添加两者图片 从左到右分别是Back和Front 将Front放到Back中心 在Front身上添加脚本 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems;//导入命名空间 public class JoyStick : MonoBehavi

  • 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 Or

  • unity实现手游虚拟摇杆

    本文实例为大家分享了unity实现手游虚拟摇杆的具体代码,供大家参考,具体内容如下 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; /// <summary> /// 绑定到摇杆上的摇杆类,参考半径50 /// </summary> public class Rocker : MonoBehaviour { Vector2 m_o

  • Unity虚拟摇杆的实现方法

    本文实例为大家分享了Unity实现虚拟摇杆的具体代码,供大家参考,具体内容如下 设置摇杆的背景图片的锚点如下: 设置摇杆的锚点为背景图片的中心点. 并给摇杆绑定脚本如下: using UnityEngine; using UnityEngine.EventSystems; using System.Collections; using System; public class JoyStickController : MonoBehaviour,IDragHandler,IEndDragHand

随机推荐