NGUI版虚拟摇杆

以下是我用nui实现的一个虚拟摇杆。

1,示图

2、代码例如以下,都有比較具体的凝视。就不说明了。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[ExecuteInEditMode]
public class Joystick : MonoBehaviour
{
    #region Delegate & Event
    public delegate void JoystickEventHandler(Joystick joystick);
    /// <summary>
    /// 开如
    /// </summary>
    public static event JoystickEventHandler On_JoystickMoveStart;
    /// <summary>
    /// Occurs when the joystick move.
    /// </summary>
    public static event JoystickEventHandler On_JoystickMove;
    /// <summary>
    /// thumb偏离中心位置。并牌按住时,每帧的回调
    /// </summary>
    public static event JoystickEventHandler On_JoystickHolding;
    /// <summary>
    /// Occurs when the joystick stops move
    /// </summary>
    public static event JoystickEventHandler On_JoystickMoveEnd;

    #endregion    

    #region   property
    [SerializeField] bool isRunInEditor = false;
    [SerializeField]private string joystickName = "NguiJoystick";
    public string JoystickName { get { return this.joystickName; } }
    [HideInInspector]private bool isLimitInCircle = true;
    public bool IsLimitInCircle { get { return this.isLimitInCircle; } }
    [SerializeField]private int radius = 100;
    public int Radius { get{ return this.radius; } }

    [SerializeField]
    private float minAlpha = 0.3f;
    public float MinAlpha { get { return this.minAlpha; } }

    private Vector2 joystickAxis = Vector2.zero;
    /// <summary>
    /// Gets the joystick axis value between -1 & 1...
    /// </summary>
    /// <value>
    /// The joystick axis.
    /// </value>
    public Vector2 JoystickAxis { get { return this.joystickAxis; } }

    private Vector2 lastJoystickAxis = Vector2.zero;
    public Vector2 LastJoystickAxis { get { return this.lastJoystickAxis; } }

    bool isForBid = false;
    /// <summary>
    /// 推断joystick是否被禁用
    /// </summary>
    public bool IsForBid { get { return this.isForBid; } }
    bool isHolding = false;
    public bool IsHolding { get { return this.isHolding; } }
    #endregion

    UIWidget root;
	[SerializeField]UISprite bg;
	[SerializeField]UISprite thumb;

    void Awake()
    {
        this.name = this.JoystickName;
        root = this.GetComponent<UIWidget>();
        Init();
    }

	// Update is called once per frame
	void Update ()
    {
        if (isRunInEditor && Application.isEditor && !Application.isPlaying)
        {
            SetJoystickSize(radius);
        }

        if (!isForBid && isHolding)
        {
            Debug.Log("111111");
            if (On_JoystickHolding != null)
            {
                On_JoystickHolding(this);
            }
        }
	}

    void Init()
    {
        bg.transform.localPosition = Vector3.zero;
        thumb.transform.localPosition = Vector3.zero;
        SetJoystickSize(radius);
        Lighting(minAlpha);
    }

	#region ngui event
    ///// <summary>
    ///// test
    ///// </summary>
    //void OnClick ()
    //{
    //    Debug.Log("mouse pos :" + Input.mousePosition + " -- touch pos :" + ScreenPos_to_NGUIPos(Input.mousePosition));
    //    thumb.transform.localPosition = ScreenPos_to_NGUIPos(Input.mousePosition);
    //}
    void OnPress (bool isPressed)
    {
        if (isForBid)
        {
            Debug.Log("joystick is forbid!");
            return;
        }
        Debug.Log("OnPress:" + isPressed.ToString());
        if(isPressed)
        {
            Lighting(1f);
            CalculateJoystickAxis();
            if (On_JoystickMoveStart != null)
            {
                On_JoystickMoveStart(this);
            }
            isHolding = true;
        }
        else
        {
            CalculateJoystickAxis();
            if (On_JoystickMoveEnd != null)
            {
                On_JoystickMoveEnd(this);
            }
            thumb.transform.localPosition = Vector3.zero;
            FadeOut(1f, minAlpha);
            isHolding = false;
        }
    }

    //void OnDragStart ()
    //{
    //    if (isForBid)
    //    {
    //        Debug.Log("joystick is forbid!");
    //        return;
    //    }

    //    Debug.Log("OnDragStart");
    //    Lighting(1f);
    //    CalculateJoystickAxis();
    //    if(On_JoystickMoveStart!=null)
    //    {
    //        On_JoystickMoveStart(this);
    //    }
	//    isHolding = true;
    //    Debug.Log(string.Format("time:{0} - axis:{1}", Time.time, joystickAxis));
    //}

    void OnDrag(Vector2 delta)
    {
        if (isForBid)
        {
            return;
        }

        //Debug.Log("OnDrag:"+delta.ToString());
        CalculateJoystickAxis();
        if (On_JoystickMoveStart != null)
        {
            On_JoystickMoveStart(this);
        }
    }

    //void OnDragEnd ()
    //{
    //    if (isForBid)
    //    {
    //        return;
    //    }

    //    Debug.Log("OnDragEnd");
    //    CalculateJoystickAxis();
    //    if (On_JoystickMoveEnd != null)
    //    {
    //        On_JoystickMoveEnd(this);
    //    }
    //    thumb.transform.localPosition = Vector3.zero;
    //    FadeOut(1f, minAlpha);
    //    isHolding = false;
    //}
	#endregion

    #region utile

    /// <summary>
    /// 计算JoystickAxis
    /// </summary>
    /// <returns></returns>
    void CalculateJoystickAxis()
    {
        Vector3 offset = ScreenPos_to_NGUIPos(UICamera.currentTouch.pos);
        offset -= transform.localPosition;
        if (isLimitInCircle)
        {
            if (offset.magnitude > radius)
            {
                offset = offset.normalized * radius;
            }
        }
        thumb.transform.localPosition = offset;

        lastJoystickAxis = joystickAxis;
        joystickAxis = new Vector2(offset.x / radius, offset.y / radius);
    }

    /// <summary>
    /// Axis2s the angle.
    /// </summary>
    /// <returns>
    /// The angle.
    /// </returns>
    public float Axis2Angle(bool inDegree = true)
    {
        float angle = Mathf.Atan2(joystickAxis.x, joystickAxis.y);

        if (inDegree)
        {
            return angle * Mathf.Rad2Deg;
        }
        else
        {
            return angle;
        }
    }

    /// <summary>
    /// Axis2s the angle.
    /// </summary>
    /// <returns>
    /// The angle.
    /// </returns>
    public float Axis2Angle(Vector2 axis, bool inDegree = true)
    {
        float angle = Mathf.Atan2(axis.x, axis.y);

        if (inDegree)
        {
            return angle * Mathf.Rad2Deg;
        }
        else
        {
            return angle;
        }
    }

    /// <summary>
    /// 屏幕坐标-->ui坐标
    /// </summary>
    /// <param name="screenPos"></param>
    /// <returns></returns>
    Vector3 ScreenPos_to_NGUIPos(Vector3 screenPos)
    {
        Vector3 uiPos = UICamera.currentCamera.ScreenToWorldPoint(screenPos);
        uiPos = UICamera.currentCamera.transform.InverseTransformPoint(uiPos);
        return uiPos;
    }

    /// <summary>
    /// 屏幕坐标-->ngui坐标
    /// </summary>
    /// <param name="screenPos"></param>
    /// <returns></returns>
    Vector3 ScreenPos_to_NGUIPos(Vector2 screenPos)
    {
        return ScreenPos_to_NGUIPos(new Vector3(screenPos.x, screenPos.y, 0f));
    }

    /// <summary>
    /// 设置摇杆的大小
    /// </summary>
    /// <param name="radius"></param>
    void SetJoystickSize(int radius)
    {
        root.width = 2 * radius;
        root.height = 2 * radius;
        thumb.width = (int)(40f / 100f * root.width);
        thumb.height = (int)(40f / 100f * root.height);
    }

    /// <summary>
    /// 点亮摇杆
    /// </summary>
    void Lighting(float alpha)
    {
        iTween.Stop(this.gameObject, "value");
        root.alpha = alpha;
    }

    /// <summary>
    /// 渐变摇杆的透明度
    /// </summary>
    void FadeOut(float fromAlpha, float toAlpha)
    {
        Hashtable itweenArgs = new Hashtable();
        itweenArgs.Add("easetype", iTween.EaseType.linear);
        itweenArgs.Add("from", fromAlpha);
        itweenArgs.Add("to", toAlpha);
        itweenArgs.Add("time", 0.5f);
        itweenArgs.Add("onupdate", "OnFadeOutTween");
        iTween.ValueTo(this.gameObject, itweenArgs);
    }
    void OnFadeOutTween(float value)
    {
        root.alpha = value;
    }

    #endregion

    #region 激活、禁用的控制
    List<string> keys = new List<string>();

   /// <summary>
    /// 禁用
   /// </summary>
   /// <returns>返回值是,取消这个禁用要用到的key</returns>
    public string ForbidJosystick()
    {
        string key = System.Guid.NewGuid().ToString();
        keys.Add(key);
        isForBid = true;
        return key;
    }

    /// <summary>
    /// 启用
    /// </summary>
    /// <param name="key"></param>
    public void ActivizeJosystick(string key)
    {
        if(keys.Contains(key))
        {
            keys.Remove(key);
        }

        isForBid = true;
        if(keys.Count==0)
        {
            isForBid = false;
        }
    }

    #endregion
}

3、demo包,有兴趣的,也能够看看。

下载:

时间: 2025-01-15 04:13:15

NGUI版虚拟摇杆的相关文章

简单的虚拟摇杆控制移动(NGUI)

一.用NGUI创建虚拟摇杆贴图 先创建一个sprite作为背景叫做JoyStick 并添加一个BoxCollider,再创建一个sprite child作为虚拟摇杆中间的按钮,叫做button 二.通过虚拟摇杆获得x,y偏移值 1 using UnityEngine; 2 using System.Collections; 3 4 public class JoyStick : MonoBehaviour 5 { 6 7 private bool isPress = false; 8 priva

【转】简单的虚拟摇杆控制移动(NGUI)

http://www.cnblogs.com/zhangbaochong/p/4928688.html 一.用NGUI创建虚拟摇杆贴图 先创建一个sprite作为背景叫做JoyStick 并添加一个BoxCollider,再创建一个sprite child作为虚拟摇杆中间的按钮,叫做button 二.通过虚拟摇杆获得x,y偏移值 1 using UnityEngine; 2 using System.Collections; 3 4 public class JoyStick : MonoBeh

unity中虚拟摇杆的实现

实现效果: 实现: 使用NGUI添加虚拟摇杆背景和其子物体按钮,为按钮Attach  boxcollider和ButtionScript.为按钮添加如下脚本: 注意:其中的静态属性可以在控制物体移动的代码中访问用于控制. 1 using UnityEngine; 2 using System.Collections; 3 4 public class joyStickControl : MonoBehaviour { 5 6 public static float h=0; 7 public s

Cocos2d-x《赵云要格斗》--虚拟摇杆控制精灵上下左右运动

本文将要实现一个横版格斗类游戏,并实现摇杆控制英雄上下左右运动.这里实现了能通过虚拟摇杆控制精灵的运动,而且能够改变精灵运动时的脸部朝向.之前看了好多人写虚拟摇杆,但是就是没写控制精灵的运动和脸朝向的.所以自己就想要写个文章好好讲下它的实现思路.好了,下面我们开始吧. 最终效果: cocos2d-x版本:2.2.5 工程环境:windows7+VS2010 打开方式:将工程放在cocos2d-x安装目录下的project文件夹下用VS打开 目录: 一.修改背景图片和窗口大小 二.添加虚拟摇杆 三

[Unity3D]Unity3D游戏开发之使用EasyTouch虚拟摇杆控制人物移动

大家好,欢迎大家关注我的博客,我是秦元培,我的博客地址是blog.csdn.net/qinyuanpei.今天呢,我们来一起学习在Unity3D中使用EasyTouch虚拟摇杆来控制人物移动.虽然Unity3D内置了一个Joystick组件(事实上就是一个GUITexture和一个Js脚本文件啦),但是博主在实际使用的时候发现这个内置的Joystick存在无法适应屏幕大小的问题,所以博主在这里向大家推荐使用EasyTouch这个插件,通过这个插件.我们能够高速地在应用中集成虚拟摇杆功能,并且能够

cocos2dx小知识——虚拟摇杆

[唠叨] 如果手机设备没有手柄.键盘的话,就只能靠触摸屏幕来操作游戏了. 虚拟摇杆的作用就是在游戏中创建几个按键来模拟手柄,通过触控来实现上下左右的移动,以及攻击.跳跃.发大招等操作. 如下所示,有一个移动的虚拟摇杆,以及一个A键. 已有开源的SneakyInput虚拟摇杆,开源地址:https://github.com/Ntran013/SneakyInput 而这里博主则是将开源的SneakyInput进一步的修改,方便博主自身的使用. [demo下载] http://down.51cto.

Cocos2d-x虚拟摇杆控制精灵上下左右运动----之游戏开发《赵云要格斗》

这是自己开发的第一次小游戏,有需要源代码和材料的邮箱留个,这里实现了能通过虚拟摇杆控制精灵的运动,而且能够改变精灵运动时的脸部朝向.之前看了好多人写虚拟摇杆,但是就是没写控制精灵的运动和脸朝向的.所以自己就想要写个文章好好讲下它的实现思路.好了,下面我们开始吧. 目录: 一.修改背景图片和窗口大小 二.添加虚拟摇杆 三.添加精灵并用摇杆控制精灵的运动 四.思路总结 一.修改背景图片和窗口大小 新建一个工程,工程名为HelloCpp.为了让效果更加好些,首先修改下窗口的大小,在main.cpp中改

Unity用UGUI做虚拟摇杆

一.首先点击UI创建两个Image,将Image的Source Image改成自己想要的Texture即可,然后在Canvas下创建一空物体,将两个Image放在空物体下作为他的子对象: 然后为可以拖动的Image编写脚本,脚本如下:(有注释,就不多说了) using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.EventSystems; public class JoyStick 

用代码写一个虚拟摇杆

找到一个以前跟老师学时,写的一个虚拟摇杆脚本,希望可以对大家有所借鉴. using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class Joystick : MonoBehaviour,IPointerDownHandler,IPointerUpHandler,IDrag