簡單的虛擬搖杆控制移動(NGUI)

來源:互聯網
上載者:User

標籤:

一、用NGUI建立虛擬搖杆貼圖

先建立一個sprite作為背景叫做JoyStick 並添加一個BoxCollider,再建立一個sprite child作為虛擬搖杆中間的按鈕,叫做button

二、通過虛擬搖杆獲得x,y位移值

 1 using UnityEngine; 2 using System.Collections; 3  4 public class JoyStick : MonoBehaviour  5 { 6  7     private bool isPress = false; 8     private Transform button; 9 10     //從虛擬搖杆的得到的x,y位移值-1到1之間11     public static float h = 0;12     public static float v = 0;13     void Awake()14     {15         button = transform.FindChild("button");16     }17     void OnPress(bool isPress)18     {19         this.isPress = isPress;20         if (!isPress)21         {22             button.localPosition = Vector2.zero;23             h = 0;24             v = 0;25         }26     }27 28     void Update()29     {30         if (isPress)31         {32             Vector2 touchPos = UICamera.lastEventPosition - new Vector2(91, 91);33             float distance = Vector2.Distance(Vector2.zero, touchPos);34             if (distance > 73)//虛擬搖桿按鍵不能超過半徑35             {36                 touchPos = touchPos.normalized * 73;37             }            38             button.localPosition = touchPos;39 40             h = touchPos.x / 73;41             v = touchPos.y / 73;42         }43     }44 }

三、通過位移控制移動 主角添加了character controller

 1 using UnityEngine; 2 using System.Collections; 3  4 public class PlayerMove : MonoBehaviour  5 { 6     private CharacterController cc; 7     public float speed = 3f; 8  9     void Awake()10     {11         cc = GetComponent<CharacterController>();12     }13     14     // Update is called once per frame15     void Update () 16     {17         //鍵盤控制18         float h = Input.GetAxis("Horizontal");19         float v = Input.GetAxis("Vertical");20 21         //虛擬搖杆控制22         if (JoyStick.h != 0 || JoyStick.v != 0)23         {24             h = JoyStick.h;25             v = JoyStick.v;26         }27 28         if (Mathf.Abs(h) > 0.1f || Mathf.Abs(v) > 0.1f)29         {30             Vector3 targetDir = new Vector3(h, 0, v);31             transform.LookAt(targetDir + transform.position);32             cc.SimpleMove(targetDir * speed);33         }34 35        36     }37 }

 

簡單的虛擬搖杆控制移動(NGUI)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.