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);
}
}
}
이렇게 하면 버튼 을 눌 러 게이머 의 이동 을 제어 할 수 있다.이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Unity 공부 일지~블렌드 셰이프 조작 방법 그 ①게임을 만들고 싶다 ~라고 생각하고 마지막 날부터 Unity를 만지기 시작했습니다 HITOMI2236입니다. 이번 블렌드 셰이프에 대해 조사했으므로 여기에 기록하려고 합니다. 개인용 메모입니다만, 만약 같은 곳에서 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.