http://blog.csdn.net/anyuanlzh/article/details/40107577

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

1,示图

2、代码如下,都有比较详细的注释,就不说明了。

  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. [ExecuteInEditMode]
  5. public class Joystick : MonoBehaviour
  6. {
  7. #region Delegate & Event
  8. public delegate void JoystickEventHandler(Joystick joystick);
  9. /// <summary>
  10. /// 开如
  11. /// </summary>
  12. public static event JoystickEventHandler On_JoystickMoveStart;
  13. /// <summary>
  14. /// Occurs when the joystick move.
  15. /// </summary>
  16. public static event JoystickEventHandler On_JoystickMove;
  17. /// <summary>
  18. /// thumb偏离中心位置,并牌按住时,每帧的回调
  19. /// </summary>
  20. public static event JoystickEventHandler On_JoystickHolding;
  21. /// <summary>
  22. /// Occurs when the joystick stops move
  23. /// </summary>
  24. public static event JoystickEventHandler On_JoystickMoveEnd;
  25. #endregion
  26. #region   property
  27. [SerializeField] bool isRunInEditor = false;
  28. [SerializeField]private string joystickName = "NguiJoystick";
  29. public string JoystickName { get { return this.joystickName; } }
  30. [HideInInspector]private bool isLimitInCircle = true;
  31. public bool IsLimitInCircle { get { return this.isLimitInCircle; } }
  32. [SerializeField]private int radius = 100;
  33. public int Radius { get{ return this.radius; } }
  34. [SerializeField]
  35. private float minAlpha = 0.3f;
  36. public float MinAlpha { get { return this.minAlpha; } }
  37. private Vector2 joystickAxis = Vector2.zero;
  38. /// <summary>
  39. /// Gets the joystick axis value between -1 & 1...
  40. /// </summary>
  41. /// <value>
  42. /// The joystick axis.
  43. /// </value>
  44. public Vector2 JoystickAxis { get { return this.joystickAxis; } }
  45. private Vector2 lastJoystickAxis = Vector2.zero;
  46. public Vector2 LastJoystickAxis { get { return this.lastJoystickAxis; } }
  47. bool isForBid = false;
  48. /// <summary>
  49. /// 判断joystick是否被禁用
  50. /// </summary>
  51. public bool IsForBid { get { return this.isForBid; } }
  52. bool isHolding = false;
  53. public bool IsHolding { get { return this.isHolding; } }
  54. #endregion
  55. UIWidget root;
  56. [SerializeField]UISprite bg;
  57. [SerializeField]UISprite thumb;
  58. void Awake()
  59. {
  60. this.name = this.JoystickName;
  61. root = this.GetComponent<UIWidget>();
  62. Init();
  63. }
  64. // Update is called once per frame
  65. void Update ()
  66. {
  67. if (isRunInEditor && Application.isEditor && !Application.isPlaying)
  68. {
  69. SetJoystickSize(radius);
  70. }
  71. if (!isForBid && isHolding)
  72. {
  73. Debug.Log("111111");
  74. if (On_JoystickHolding != null)
  75. {
  76. On_JoystickHolding(this);
  77. }
  78. }
  79. }
  80. void Init()
  81. {
  82. bg.transform.localPosition = Vector3.zero;
  83. thumb.transform.localPosition = Vector3.zero;
  84. SetJoystickSize(radius);
  85. Lighting(minAlpha);
  86. }
  87. #region ngui event
  88. ///// <summary>
  89. ///// test
  90. ///// </summary>
  91. //void OnClick ()
  92. //{
  93. //    Debug.Log("mouse pos :" + Input.mousePosition + " -- touch pos :" + ScreenPos_to_NGUIPos(Input.mousePosition));
  94. //    thumb.transform.localPosition = ScreenPos_to_NGUIPos(Input.mousePosition);
  95. //}
  96. void OnPress (bool isPressed)
  97. {
  98. if (isForBid)
  99. {
  100. Debug.Log("joystick is forbid!");
  101. return;
  102. }
  103. Debug.Log("OnPress:" + isPressed.ToString());
  104. if(isPressed)
  105. {
  106. Lighting(1f);
  107. CalculateJoystickAxis();
  108. if (On_JoystickMoveStart != null)
  109. {
  110. On_JoystickMoveStart(this);
  111. }
  112. isHolding = true;
  113. }
  114. else
  115. {
  116. CalculateJoystickAxis();
  117. if (On_JoystickMoveEnd != null)
  118. {
  119. On_JoystickMoveEnd(this);
  120. }
  121. thumb.transform.localPosition = Vector3.zero;
  122. FadeOut(1f, minAlpha);
  123. isHolding = false;
  124. }
  125. }
  126. //void OnDragStart ()
  127. //{
  128. //    if (isForBid)
  129. //    {
  130. //        Debug.Log("joystick is forbid!");
  131. //        return;
  132. //    }
  133. //    Debug.Log("OnDragStart");
  134. //    Lighting(1f);
  135. //    CalculateJoystickAxis();
  136. //    if(On_JoystickMoveStart!=null)
  137. //    {
  138. //        On_JoystickMoveStart(this);
  139. //    }
  140. //    isHolding = true;
  141. //    Debug.Log(string.Format("time:{0} - axis:{1}", Time.time, joystickAxis));
  142. //}
  143. void OnDrag(Vector2 delta)
  144. {
  145. if (isForBid)
  146. {
  147. return;
  148. }
  149. //Debug.Log("OnDrag:"+delta.ToString());
  150. CalculateJoystickAxis();
  151. if (On_JoystickMoveStart != null)
  152. {
  153. On_JoystickMoveStart(this);
  154. }
  155. }
  156. //void OnDragEnd ()
  157. //{
  158. //    if (isForBid)
  159. //    {
  160. //        return;
  161. //    }
  162. //    Debug.Log("OnDragEnd");
  163. //    CalculateJoystickAxis();
  164. //    if (On_JoystickMoveEnd != null)
  165. //    {
  166. //        On_JoystickMoveEnd(this);
  167. //    }
  168. //    thumb.transform.localPosition = Vector3.zero;
  169. //    FadeOut(1f, minAlpha);
  170. //    isHolding = false;
  171. //}
  172. #endregion
  173. #region utile
  174. /// <summary>
  175. /// 计算JoystickAxis
  176. /// </summary>
  177. /// <returns></returns>
  178. void CalculateJoystickAxis()
  179. {
  180. Vector3 offset = ScreenPos_to_NGUIPos(UICamera.currentTouch.pos);
  181. offset -= transform.localPosition;
  182. if (isLimitInCircle)
  183. {
  184. if (offset.magnitude > radius)
  185. {
  186. offset = offset.normalized * radius;
  187. }
  188. }
  189. thumb.transform.localPosition = offset;
  190. lastJoystickAxis = joystickAxis;
  191. joystickAxis = new Vector2(offset.x / radius, offset.y / radius);
  192. }
  193. /// <summary>
  194. /// Axis2s the angle.
  195. /// </summary>
  196. /// <returns>
  197. /// The angle.
  198. /// </returns>
  199. public float Axis2Angle(bool inDegree = true)
  200. {
  201. float angle = Mathf.Atan2(joystickAxis.x, joystickAxis.y);
  202. if (inDegree)
  203. {
  204. return angle * Mathf.Rad2Deg;
  205. }
  206. else
  207. {
  208. return angle;
  209. }
  210. }
  211. /// <summary>
  212. /// Axis2s the angle.
  213. /// </summary>
  214. /// <returns>
  215. /// The angle.
  216. /// </returns>
  217. public float Axis2Angle(Vector2 axis, bool inDegree = true)
  218. {
  219. float angle = Mathf.Atan2(axis.x, axis.y);
  220. if (inDegree)
  221. {
  222. return angle * Mathf.Rad2Deg;
  223. }
  224. else
  225. {
  226. return angle;
  227. }
  228. }
  229. /// <summary>
  230. /// 屏幕坐标-->ui坐标
  231. /// </summary>
  232. /// <param name="screenPos"></param>
  233. /// <returns></returns>
  234. Vector3 ScreenPos_to_NGUIPos(Vector3 screenPos)
  235. {
  236. Vector3 uiPos = UICamera.currentCamera.ScreenToWorldPoint(screenPos);
  237. uiPos = UICamera.currentCamera.transform.InverseTransformPoint(uiPos);
  238. return uiPos;
  239. }
  240. /// <summary>
  241. /// 屏幕坐标-->ngui坐标
  242. /// </summary>
  243. /// <param name="screenPos"></param>
  244. /// <returns></returns>
  245. Vector3 ScreenPos_to_NGUIPos(Vector2 screenPos)
  246. {
  247. return ScreenPos_to_NGUIPos(new Vector3(screenPos.x, screenPos.y, 0f));
  248. }
  249. /// <summary>
  250. /// 设置摇杆的大小
  251. /// </summary>
  252. /// <param name="radius"></param>
  253. void SetJoystickSize(int radius)
  254. {
  255. root.width = 2 * radius;
  256. root.height = 2 * radius;
  257. thumb.width = (int)(40f / 100f * root.width);
  258. thumb.height = (int)(40f / 100f * root.height);
  259. }
  260. /// <summary>
  261. /// 点亮摇杆
  262. /// </summary>
  263. void Lighting(float alpha)
  264. {
  265. iTween.Stop(this.gameObject, "value");
  266. root.alpha = alpha;
  267. }
  268. /// <summary>
  269. /// 渐变摇杆的透明度
  270. /// </summary>
  271. void FadeOut(float fromAlpha, float toAlpha)
  272. {
  273. Hashtable itweenArgs = new Hashtable();
  274. itweenArgs.Add("easetype", iTween.EaseType.linear);
  275. itweenArgs.Add("from", fromAlpha);
  276. itweenArgs.Add("to", toAlpha);
  277. itweenArgs.Add("time", 0.5f);
  278. itweenArgs.Add("onupdate", "OnFadeOutTween");
  279. iTween.ValueTo(this.gameObject, itweenArgs);
  280. }
  281. void OnFadeOutTween(float value)
  282. {
  283. root.alpha = value;
  284. }
  285. #endregion
  286. #region 激活、禁用的控制
  287. List<string> keys = new List<string>();
  288. /// <summary>
  289. /// 禁用
  290. /// </summary>
  291. /// <returns>返回值是,取消这个禁用要用到的key</returns>
  292. public string ForbidJosystick()
  293. {
  294. string key = System.Guid.NewGuid().ToString();
  295. keys.Add(key);
  296. isForBid = true;
  297. return key;
  298. }
  299. /// <summary>
  300. /// 启用
  301. /// </summary>
  302. /// <param name="key"></param>
  303. public void ActivizeJosystick(string key)
  304. {
  305. if(keys.Contains(key))
  306. {
  307. keys.Remove(key);
  308. }
  309. isForBid = true;
  310. if(keys.Count==0)
  311. {
  312. isForBid = false;
  313. }
  314. }
  315. #endregion
  316. }

3、demo包,有兴趣的,也可以看看。

下载:

 
 

【转】NGUI版虚拟摇杆的更多相关文章

  1. NGUI版虚拟摇杆

    以下是我用nui实现的一个虚拟摇杆. 1,示图 2.代码例如以下,都有比較具体的凝视.就不说明了. using UnityEngine; using System.Collections; using ...

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

    http://www.cnblogs.com/zhangbaochong/p/4928688.html 一.用NGUI创建虚拟摇杆贴图 先创建一个sprite作为背景叫做JoyStick 并添加一个B ...

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

    一.用NGUI创建虚拟摇杆贴图 先创建一个sprite作为背景叫做JoyStick 并添加一个BoxCollider,再创建一个sprite child作为虚拟摇杆中间的按钮,叫做button 二.通 ...

  4. unity中虚拟摇杆的实现

    实现效果: 实现: 使用NGUI添加虚拟摇杆背景和其子物体按钮,为按钮Attach  boxcollider和ButtionScript.为按钮添加如下脚本: 注意:其中的静态属性可以在控制物体移动的 ...

  5. Unity3d项目入门之虚拟摇杆

    Unity本身不提供摇杆的组件,开发者可以使用牛逼的EasyTouch插件或者应用NGUI实现相关的需求,下面本文通过Unity自身的UGUI属性,实现虚拟摇杆的功能. 主参考 <Unity:使 ...

  6. Unity 使用有限状态机 完美还原 王者荣耀 虚拟摇杆

    Unity 使用有限状态机 完美还原 王者荣耀 虚拟摇杆 效果如图所示 摇杆的UI组成 如图所示 简单的可以认为摇杆由1.2.3贴图组成 为摇杆的底座 为摇杆的杆 为摇杆的指向 可以理解这就是街机上的 ...

  7. 【转】Unity3D学习日记(二)使用UGUI制作虚拟摇杆控制摄像机

    http://blog.csdn.net/begonia__z/article/details/51178907 前天撸了一个简单的UGUI虚拟摇杆,今天我就利用前天做的虚拟摇杆做了一个简单的摄像机控 ...

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

    大家好,欢迎大家关注我的博客,我是秦元培,我的博客地址是blog.csdn.net/qinyuanpei.今天呢,我们来一起学习在Unity3D中使用EasyTouch虚拟摇杆来控制人物移动.虽然Un ...

  9. unity零基础开始学习做游戏(三)鼠标输入,来个虚拟摇杆怎么样?

    -------小基原创,转载请给我一个面子 现在移动游戏越来越火,大家都拿手机平板玩游戏,没有键盘和手柄输入,所以就不得不看看虚拟摇杆怎么搞?(小基对于没有实体反馈不是很喜欢呢) 首先要清楚,鼠标操作 ...

随机推荐

  1. Linux重定向命令

    linux重定向命令应用及语法  [复制链接]   发表于 2008-12-18 18:24 | 来自  51CTO网页 [只看他] 楼主     1. 标准输入的控制语法:命令 文件将命令的执行结果 ...

  2. C# params参数的应用

    为了将方法声明为可以接受可变数量参数的方法,我们可以使用params关键字来声明数组,如下所示: public static Int32Add(params Int32[] values) { Int ...

  3. ACM-ICPC国际大学生程序设计竞赛北京赛区(2015)网络赛 B Mission Impossible 6

    #1228 : Mission Impossible 6 时间限制:1000ms 单点时限:1000ms 内存限制:256MB 描述 You must have seen the very famou ...

  4. 【SPOJ】7258. Lexicographical Substring Search(后缀自动机)

    http://www.spoj.com/problems/SUBLEX/ 后缀自动机系列完成QAQ...撒花..明天or今晚写个小结? 首先得知道:后缀自动机中,root出发到任意一个状态的路径对应一 ...

  5. BZOJ4129: Haruna’s Breakfast

    Description Haruna每天都会给提督做早餐! 这天她发现早饭的食材被调皮的 Shimakaze放到了一棵 树上,每个结点都有一样食材,Shimakaze要考验一下她. 每个食材都有一个美 ...

  6. 在Copy-Item中集成认证信息以拷贝文件

    $source = "c:\XXX.XXX" $pw = ConvertTo-SecureString '密码' -AsPlainText -Force $Creds = New- ...

  7. replication set复制集

    replication set复制集  介绍 replicattion set 多台服务器维护相同的数据副本,提高服务器的可用性,总结下来有以下好处: 数据备份与恢复 读写分离 MongoDB 复制集 ...

  8. 数据库存储txt文本和jpg图片

    环境:MySql+SQLyog+j2se+jdbc 存储文本用longtext类型 存储图片用blob类型 1.首先建表 create table t_t (id int(16) NOT NULL A ...

  9. PAT (Advanced Level) Practise 1003 Emergency(SPFA+DFS)

    1003. Emergency (25) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue As an emerg ...

  10. 交叉报表列头排序时遇到的oracle问题—oracle ORA-12704:字符集不匹配、varchar2转化为nvarchar2字符缺失、case when else后的字符类型要一致

    在做交叉报表列头的排序时,遇到这三个问题,下面具体来说一下. 设计的数据库的表结构如图1所示: 图1 要处出来student_name_,s.grade_,s.subject_name_,这三个属性, ...