Unity3D 가상 버튼 으로 캐릭터 이동 제어 효과 구현

본 고 는 Unity3D 가 가상 버튼 을 실현 하여 인물 의 이동 을 제어 하 는 구체 적 인 코드 를 공유 하여 여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.
Image 의 UI 구성 요 소 를 만 들 고 Image 아래 버튼 을 새로 만 듭 니 다.Image 와 Button 에 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  ,      
 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);
 
   //  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;
  }
 
 }
 
 //       
 public void OnPointerDown(PointerEventData eventData) {
  isPress = true;
 }
 
 //         
 public void OnPointerUp(PointerEventData eventData)
 {
  isPress = false;
  transform.localPosition = Vector3.zero;
 }
 
}
유저 에 게 유저 의 이동 을 제어 하 는 스 크 립 트 를 마 운 트 합 니 다

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() {
  //             ,         
  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");
  }
  //      
  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);
  }
  
 }
}
이렇게 하면 버튼 을 눌 러 게이머 의 이동 을 제어 할 수 있다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기