PlayerMove.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
private float _horizontalInput;
private float _verticalInput;
private float _movespeed = 3f;
private Rigidbody2D rigid;
private CapsuleCollider2D _capsuleCollider2D;
public Animator _animator;
void Start()
{
rigid = GetComponent<Rigidbody2D>();
_capsuleCollider2D = GetComponent<CapsuleCollider2D>();
_animator = GetComponent<Animator>();
}
void Update()
{
// 개발자 디버그용 w, a, s, d 이동
_horizontalInput = Input.GetAxisRaw("Horizontal");
_verticalInput = Input.GetAxisRaw("Vertical");
// 입력이 있다면 moveState로 전환, 없다면 전환 X
if (_horizontalInput != 0 || _verticalInput != 0)
{
_animator.SetBool("isMove", true);
}
else
{
_animator.SetBool("isMove", false);
}
_animator.SetFloat("Vertical_Input", _verticalInput);
_animator.SetFloat("Horizontal_Input", _horizontalInput);
transform.Translate(new Vector2(_horizontalInput, _verticalInput) * (Time.deltaTime * _movespeed));
}
}
virtual joystick.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class VirtualJoystick : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
[SerializeField, Range(10, 150)]
private float leverRange;
[SerializeField]
private RectTransform lever;
private RectTransform _rectTransform;
//플레이어 이동 구현
private PlayerMove _playerMove;
private Vector2 inputDir;
private bool isInput;
private float _movespeed = 3f;
private void Awake()
{
_rectTransform = GetComponent<RectTransform>();
_playerMove = GameObject.Find("Player").GetComponent<PlayerMove>();
}
private void Update()
{
if (isInput)
{
InputControlVector();
}
}
public void OnBeginDrag(PointerEventData eventData)
{
ControlJoystickLevel(eventData);
isInput = true;
}
public void OnDrag(PointerEventData eventData)
{
ControlJoystickLevel(eventData);
}
public void OnEndDrag(PointerEventData eventData)
{
lever.anchoredPosition = Vector2.zero;
isInput = false;
_playerMove._animator.SetBool("isMove", false);
}
void ControlJoystickLevel(PointerEventData eventData)
{
var inputPos = eventData.position - _rectTransform.anchoredPosition;
// inputPos의 길이와 leverRange 길이 비교
var inputVector = inputPos.magnitude < leverRange ? inputPos : inputPos.normalized * leverRange;
lever.anchoredPosition = inputVector;
// inputVector는 해상도는 기반으로 만들어진 벡터라 그냥 쓰기엔 너무 큼
inputDir = inputVector / leverRange;
}
void InputControlVector()
{
_playerMove._animator.SetBool("isMove", true);
_playerMove._animator.SetFloat("Vertical_Input", inputDir.y);
_playerMove._animator.SetFloat("Horizontal_Input", inputDir.x);
_playerMove.gameObject.transform.Translate(new Vector2(inputDir.x, inputDir.y) * (Time.deltaTime * _movespeed));
}
}