原创内容,转载请注明原文网址:http://homeqin.cn/a/wenzhangboke/jishutiandi/youxikaifa/2018/1223/260.html
常州手机游戏App开发-简单的虚拟摇杆控制移动(NGUI)
一、用NGUI创建虚拟摇杆贴图
先创建一个sprite作为背景叫做JoyStick 并添加一个BoxCollider,再创建一个sprite child作为虚拟摇杆中间的按钮,叫做button
二、通过常州平台运营虚拟摇杆获得x,y偏移值
	using UnityEngine;
	using System.Collections;
	public class JoyStick : MonoBehaviour 
	{
	    private bool isPress = false;
	    private Transform button;
	    //从虚拟摇杆的得到的x,y偏移值-1到1之间
	    public static float h = 0;
	    public static float v = 0;
	    void Awake()
	    {
	        button = transform.FindChild("button");
	    }
	    void OnPress(bool isPress)
	    {
	        this.isPress = isPress;
	        if (!isPress)
	        {
	            button.localPosition = Vector2.zero;
	            h = 0;
	            v = 0;
	        }
	    }
	    void Update()
	    {
	        if (isPress)
	        {
	            Vector2 touchPos = UICamera.lastEventPosition - new Vector2(91, 91);
	            float distance = Vector2.Distance(Vector2.zero, touchPos);
	            if (distance > 73)//常州微信小程序开发虚拟摇杆按钮不能超过半径
	            {
	                touchPos = touchPos.normalized * 73;
	            }            
	            button.localPosition = touchPos;
	            h = touchPos.x / 73;
	            v = touchPos.y / 73;
	        }
	    }
	}
	
	三、通过偏移控制移动 主角添加了character controller
	using UnityEngine;
	using System.Collections;
	public class PlayerMove : MonoBehaviour 
	{
	    private CharacterController cc;
	    public float speed = 3f;
	    void Awake()
	    {
	        cc = GetComponent<CharacterController>();
	    }
	    // Update is called once per frame
	    void Update () 
	    {
	        //键盘控制
	        float h = Input.GetAxis("Horizontal");
	        float v = Input.GetAxis("Vertical");
	        //虚拟摇杆控制
	        if (JoyStick.h != 0 || JoyStick.v != 0)
	        {
	            h = JoyStick.h;
	            v = JoyStick.v;
	        }
	        if (Mathf.Abs(h) > 0.1f || Mathf.Abs(v) > 0.1f)
	        {
	            Vector3 targetDir = new Vector3(h, 0, v);
	            transform.LookAt(targetDir + transform.position);
	            cc.SimpleMove(targetDir * speed);
	        }
	    }
	}
上篇:上一篇:常州网站技术微信平台-c++分割字符串
下篇:下一篇:常州微信小程序开发:实现一种类似List<T>的数据




