码迷,mamicode.com
首页 > 编程语言 > 详细

unity中虚拟摇杆的实现

时间:2016-05-17 22:29:47      阅读:904      评论:0      收藏:0      [点我收藏+]

标签:

实现效果:

技术分享


 

实现:

使用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相一致。
 

技术分享

unity中虚拟摇杆的实现

标签:

原文地址:http://www.cnblogs.com/Firepad-magic/p/5503347.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!