溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Unity3D實(shí)現(xiàn)虛擬按鈕控制人物移動(dòng)效果

發(fā)布時(shí)間:2020-09-20 02:48:20 來(lái)源:腳本之家 閱讀:231 作者:shenqingyu0605202324 欄目:編程語(yǔ)言

本文為大家分享了Unity3D實(shí)現(xiàn)虛擬按鈕控制人物移動(dòng)的具體代碼,供大家參考,具體內(nèi)容如下

創(chuàng)建Image的UI組件,在Image下新建一個(gè)Button按鈕。在Image 和Button上拖進(jìn)Sprite圖片

Unity3D實(shí)現(xiàn)虛擬按鈕控制人物移動(dòng)效果

在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è)虛擬按鍵有沒有移動(dòng),沒有再選擇鍵盤輸入
  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í)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI