Unity3D基于NGUI的虚拟摇杆实现
发表于2018-05-25
现在大家玩的很多手机游戏,都喜欢使用虚拟摇杆功能,对于玩家来说操作体验肯定很棒,但对于开发者来说,如何制作虚拟摇杆功能才是他们需要思考的,下面就和大家介绍下基于NGUI的虚拟摇杆实现。
实现效果预览

C#代码
实现:使用NGUI添加虚拟摇杆背景和其子物体按钮,为按钮Attach boxcollider和ButtionScript。为按钮添加如下脚本:
注意:其中的静态属性可以在控制物体移动的代码中访问用于控制。
using UnityEngine; using System.Collections; public class joyStickControl : MonoBehaviour { public static float h=0; public static float v = 0; private float parentHeight; private float parentWidth; private bool isPress=false; UISprite parentSpirite; void Awake() { parentSpirite = transform.parent.GetComponent<UISprite>(); parentWidth = parentSpirite.width; parentHeight = parentSpirite.height; } // Update is called once per frame void Update () { // 触摸按下 if (isPress) { Vector2 touchpos = UICamera.lastTouchPosition; // 默认情况下,坐标原点位于父精灵左下角,下面的代码是调整原点到父物体中心 touchpos -=new Vector2(parentWidth / 2, parentHeight / 2); // 计算原点和触摸点的距离 float distance = Vector2.Distance(touchpos, Vector2.zero); if(distance<53)// 距离在父精灵背景中圆内,53为其半径 { transform.localPosition = touchpos; } else {// 触摸点到原点的距离超过半径,则把子精灵按钮的位置设置为在父精灵背景的圆上,即控制摇杆只能在父精灵圆内移动 transform.localPosition = touchpos.normalized * 53; } // h和v返回[-1, 1]的数字,分别为水平和竖直方向 h = transform.localPosition.x / 53; v = transform.localPosition.y / 53; } else {// 触摸抬起,那么把按钮位置恢复到原点 transform.localPosition = Vector2.zero; h = 0;v = 0; } } // 触摸按下,isPress为true;抬起为false void OnPress(bool isPress) { // 保存标志位:按下或抬起,用于在Update方法中判断触摸是否按下 this.isPress = isPress; } }
控制物体移动的代码:
注意:在使用虚拟摇杆的时候则忽略键盘控制的移动操作。
using UnityEngine; using System.Collections; public class MoveCtroller : MonoBehaviour { private float speed = 3; // Use this for initialization void Start () { } // Update is called once per frame void Update () { // 得到键盘上的水平和竖直方向,wasd和上下左右键 float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); // 优先使用摇杆控制角色移动 if (joyStickControl.h!=0||joyStickControl.v!=0) { h = joyStickControl.h; v = joyStickControl.v; } if (Mathf.Abs(h)>0.3||Mathf.Abs(v)>0.3) { GetComponent<CharacterController>().SimpleMove(new Vector3(h * speed, 0, v * speed)); } } }
注意: normalized的属性获取当前向量的方向向量,在这里transform.localPosition = touchpos.normalized * 53; 用于使按钮保持在虚拟摇杆背景圆的范围类。
touchpos -=new Vector2(parentWidth / 2, parentHeight / 2);则是为了将触点位置与中心按钮的localpositon相一致。
