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 static float v = 0; 8 9 private float parentHeight; 10 private float parentWidth; 11 12 private bool isPress=false; 13 14 UISprite parentSpirite; 15 16 void Awake() 17 { 18 parentSpirite = transform.parent.GetComponent<UISprite>(); 19 parentWidth = parentSpirite.width; 20 parentHeight = parentSpirite.height; 21 } 22 23 24 // Update is called once per frame 25 void Update () { 26 27 if (isPress) 28 { 29 Vector2 touchpos = UICamera.lastTouchPosition; 30 31 touchpos -=new Vector2(parentWidth / 2, parentHeight / 2); 32 float distance = Vector2.Distance(touchpos, Vector2.zero); 33 if(distance<53) 34 { 35 transform.localPosition = touchpos; 36 } 37 else 38 { 39 transform.localPosition = touchpos.normalized * 53; 40 } 41 42 h = transform.localPosition.x / 53; 43 v = transform.localPosition.y / 53; 44 45 } 46 else 47 { 48 transform.localPosition = Vector2.zero; 49 h = 0; 50 v = 0; 51 } 52 53 } 54 55 void OnPress(bool isPress) 56 { 57 this.isPress = isPress; 58 } 59 }
控制物体移动的代码:
注意:在使用虚拟摇杆的时候则忽略键盘控制的移动操作。
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 () { 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相一致。
Easy Touch 这个插件想必很多人都有所耳闻,可以迅速实现触摸操作。很适合移动端游戏的触摸输入控制,支持触摸,点击,拖拽,两指缩放。想要节省移动端游戏输入开发的时间可以下载使用
作者:世纪末的魔术师
出处:https://www.cnblogs.com/Firepad-magic/
Unity最受欢迎插件推荐:点击查看
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)