Unity3D實(shí)現(xiàn)虛擬按鈕控制人物移動(dòng)效果
本文為大家分享了Unity3D實(shí)現(xiàn)虛擬按鈕控制人物移動(dòng)的具體代碼,供大家參考,具體內(nèi)容如下
創(chuàng)建Image的UI組件,在Image下新建一個(gè)Button按鈕。在Image 和Button上拖進(jìn)Sprite圖片
在Button按鈕上掛載該腳本
using System.Collections; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class MyJoystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler { public Canvas canvas; public static float h; //h和v的值傳回給player腳本,使得物體移動(dòng) public static float v; private bool isPress = false; //Button按鈕是否按下 private Vector2 touchPos = Vector2.zero; //按下的位置 void Update() { if (isPress) { RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, Input.mousePosition, null, out touchPos); //根據(jù)Canvas和Image的Rectransform位置相減得出 touchPos += new Vector2(427, 299); float distance = Vector2.Distance(Vector2.zero, touchPos); if (distance > 52) { //限制Button不能超出Image位置(兩者位置相減得出52) touchPos = touchPos.normalized*52; transform.localPosition = touchPos; } else { transform.localPosition = touchPos; } h = touchPos.x / 52; v = touchPos.y / 52; } } //鼠標(biāo)按下時(shí)觸發(fā) public void OnPointerDown(PointerEventData eventData) { isPress = true; } //鼠標(biāo)按鍵彈起時(shí)觸發(fā) public void OnPointerUp(PointerEventData eventData) { isPress = false; transform.localPosition = Vector3.zero; } }
在玩家身上掛載控制玩家移動(dòng)的腳本
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMove : MonoBehaviour { public float speed = 0.1f; private float h = 0; private float v = 0; void Update() { //首先檢測(cè)虛擬按鍵有沒(méi)有移動(dòng),沒(méi)有再選擇鍵盤輸入 if (Mathf.Abs(MyJoystick.h) > 0 || Mathf.Abs(MyJoystick.v) > 0) { h = MyJoystick.h; v = MyJoystick.v; } else{ h = Input.GetAxis("Horizontal"); v = Input.GetAxis("Vertical"); } //玩家位置移動(dòng) if (Mathf.Abs(h) > 0.1 || Mathf.Abs(v) > 0.1) { Vector3 targetDir = new Vector3(h, 0, v); transform.position += targetDir * speed; transform.LookAt(transform.position+targetDir); } } }
這樣,就能通過(guò)按下Button來(lái)控制玩家移動(dòng)了。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C# Fiddler插件實(shí)現(xiàn)網(wǎng)站離線瀏覽功能
本文主要介紹了C# Fiddler插件實(shí)現(xiàn)網(wǎng)站離線瀏覽功能的原理與方法。具有很好的參考價(jià)值,下面跟著小編一起來(lái)看下吧2017-02-02淺談C#各種數(shù)組直接的數(shù)據(jù)復(fù)制/轉(zhuǎn)換
下面小編就為大家?guī)?lái)一篇淺談C#各種數(shù)組直接的數(shù)據(jù)復(fù)制/轉(zhuǎn)換。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-08-08在Framework 4.0中:找出新增的方法與新增的類(一)
經(jīng)??吹接型瑢W(xué)在討論Framework 4 的新特性,新方法,于是想寫個(gè)程序找出framework4.0中新增的方法和類2013-05-05C#實(shí)現(xiàn)根據(jù)銀行卡卡號(hào)判斷銀行名
這篇文章主要介紹了C#實(shí)現(xiàn)根據(jù)銀行卡卡號(hào)判斷銀行名,是從其他網(wǎng)友的java程序改編而來(lái),有需要的小伙伴可以參考下。2015-07-07c#根據(jù)文件類型獲取相關(guān)類型圖標(biāo)的方法代碼
c#根據(jù)文件類型獲取相關(guān)類型圖標(biāo)的方法代碼,需要的朋友可以參考一下2013-05-05C#配置log4net實(shí)現(xiàn)將日志分類記錄到不同的日志文件中
log4net是.Net下一個(gè)非常優(yōu)秀的開(kāi)源日志記錄組件,log4net記錄日志的功能非常強(qiáng)大,它可以將日志分不同的等級(jí),以不同的格式,輸出到不同的媒介,下面我們就來(lái)看看C#如何配置log4net讓日志分類記錄到不同的日志文件吧2024-02-02