博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
unity中虚拟摇杆的实现
阅读量:4608 次
发布时间:2019-06-09

本文共 2567 字,大约阅读时间需要 8 分钟。

实现效果:


 

实现:

使用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
();19 parentWidth = parentSpirite.width;20 parentHeight = parentSpirite.height;21 }22 23 24 // Update is called once per frame25 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 else38 {39 transform.localPosition = touchpos.normalized * 53;40 }41 42 h = transform.localPosition.x / 53;43 v = transform.localPosition.y / 53;44 45 }46 else47 {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
().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/p/5503347.html

你可能感兴趣的文章