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

编程入门 行业动态 更新时间:2024-10-28 03:19:01

在unity3d中开发虚拟摇杆方式有比较多,可以使用easytouch、fairygui等插件来开发。本文给大家介绍使用unity3d的原生ugui来开发出自己的虚拟摇杆,这样可以减少游戏资源包的大小。

先展示下效果图:

现在开发我们的开发

创建一个image1,并且在image1创建一个子对象image2

在image1中挂载一个自定义脚本,这里我命名为joystick

脚本代码如下

using system.collections;using system.collections.generic;using unityengine;using unityengine.eventsystems;using unityengine.ui; public class joystick : scrollrect{ private float mradius; public system.action<recttransform> joystickmovehandle; public system.action<recttransform> joystickendhandle; protected override void start() { mradius = this.getcomponent<recttransform>().sizedelta.x * 0.5f; this.content.gameobject.setactive(false); } public override void ondrag(pointereventdata eventdata) { base.ondrag(eventdata); this.content.gameobject.setactive(true); //虚拟摇杆移动 var contentpostion = this.content.anchoredposition; if (contentpostion.magnitude > mradius) { contentpostion = contentpostion.normalized * mradius; setcontentanchoredposition(contentpostion); } //旋转 if (content.anchoredposition.y != 0) { content.eulerangles = new vector3(0, 0, vector3.angle(vector3.right, content.anchoredposition) * content.anchoredposition.y / mathf.abs(content.anchoredposition.y) - 90); } } private void fixedupdate() { if (this.content.gameobject.activeinhierarchy) { if (joystickmovehandle != null) { joystickmovehandle(this.content); } } } public override void onenddrag(pointereventdata eventdata) { base.onenddrag(eventdata); this.content.gameobject.setactive(false); if (joystickendhandle != null) { joystickendhandle(this.content); } }}

然后将image2拖动到content属性变量里

这样就可以移动并且拖动我们的虚拟摇杆了

接下来要让我们的游戏主角跟随我们的摇杆移动而移动

在我们的主角儿挂载一个自定义脚本

在start方法里添加代码:

mjoystick = gameobject.find("joystick").getcomponent<joystick>(); mjoystick.joystickmovehandle = joystickhandle; mjoystick.joystickendhandle = joystickendhandle;

其中joystickhandle方法代码为:

transform.eulerangles = new vector3(0, -content.eulerangles.z, 0); transform.translate(vector3.forward * time.deltatime * mmovespeed);

接下来就可以运行我们的游戏,观察主角移动旋转位置。

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

  • 0
  • 0
  • 0
  • 0
  • 0

更多推荐

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

本文发布于:2023-06-10 22:57:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/620879.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:摇杆   Unity3D   UGUI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!