您的位置:首页 > 移动开发 > Unity3D

【Unity】用NGUI实现摇杆功能

2015-03-04 16:00 901 查看
using UnityEngine;

using System.Collections;

public class Joystick : MonoBehaviour 

{

    private bool Ispress = false;

    private Transform button;

    public static float h = 0;

    public static float v = 0;

    

    void Awake()

    {

        button = transform.Find("Button");

        

    }

    

    void OnPress(bool isPress) //按下触发函数 isPress就为真

    {

        this.Ispress = isPress;

        if (Ispress == false)

        {

        button.localPosition = Vector3.zero;

        h = 0;  //鼠标抬起归零

        v = 0;  //鼠标抬起归零

        }

    }

    void Update()

    {

        

        if (this.Ispress) //当触发的时候

        {

            //print(UICamera.lastTouchPosition);

            Vector2 touchPos = UICamera.lastTouchPosition; //记录上一次的触摸位置

            //print(touchPos);

            touchPos -= new Vector2(91, 91);  //让按钮的原点定于中心店

            float distance = Vector2.Distance(Vector2.zero, touchPos); //上次触摸坐标和原点的距离

            if (distance > 73)  //如果大于的话,就让BUTTON的本地坐标等于上次触发的坐标TOUCHPOS

            {

                touchPos = touchPos.normalized * 73;

                button.localPosition = touchPos;

            }

            else

            {

                button.localPosition = touchPos;

                // print(touchPos);

            }

            h = touchPos.x / 73;

            v = touchPos.y / 73;

        }

       // print("h的坐标为:"+h+"    v的坐标为:"+v);

        

    }

   

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: