Unity3d 基于NGUI的虚拟摇杆实现
来源:互联网 发布:小米笔记本office软件 编辑:程序博客网 时间:2024/06/11 00:27
实现效果预览
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相一致。
原帖:unity中虚拟摇杆的实现
0 0
- Unity3d 基于NGUI的虚拟摇杆实现
- 基于Unity3D的虚拟摇杆的实现
- Unity3D基于UGUI的虚拟摇杆实现
- Unity3D 虚拟摇杆 NGUI实现方法
- Unity3d中利用NGUI实现虚拟摇杆
- NGUI版虚拟摇杆
- Unity3D NGUI屏幕摇杆
- 使用Easy Touch 实现unity3d 虚拟摇杆
- UGUI 虚拟摇杆的实现
- unity虚拟摇杆的实现
- unity3d 虚拟摇杆
- Unity3D 虚拟摇杆(之一)
- Unity3D之虚拟摇杆
- NGUI版虚拟摇杆joystick
- NGUI自制简易虚拟摇杆
- Unity3D 双摇杆 c# JoyStick 实现自己的双摇杆
- Unity3D 虚拟摇杆 Easy Touch
- android虚拟手柄摇杆的实现
- 【转载】通过 FUNCTION NET_DUE_DATE_GET 得到MIRO付款日期(DUE ON DATE)
- SQLCookBook第三章学习日记9
- 回顾一下模板
- linux du命令参数及用法详解---linux统计磁盘空间大小命令
- Vijos P1056 图形面积
- Unity3d 基于NGUI的虚拟摇杆实现
- PHP命名空间的名称解析规则
- ZooKeeper
- AVAudioPlayer实现音乐播放+歌词与播放进度同步
- maven报错解决方案集
- XCODE jsonMODEL对换数据
- 欢迎使用CSDN-markdown编辑器
- 【转载】Java泛型中E、T、K、V等的含义
- eclipse validating 卡着一直不动