Joystick ảo trên màn hình cảm ứng
C# Code
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class TouchJoystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler
{
public Image joystickBackground;
public Image joystickHandle;
private Vector2 inputVector;
public Vector2 InputVector => inputVector; // Dùng để các script khác lấy giá trị
public void OnPointerDown(PointerEventData eventData)
{
OnDrag(eventData);
}
public void OnDrag(PointerEventData eventData)
{
Vector2 pos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(joystickBackground.rectTransform, eventData.position, eventData.pressEventCamera, out pos))
{
pos.x = (pos.x / joystickBackground.rectTransform.sizeDelta.x);
pos.y = (pos.y / joystickBackground.rectTransform.sizeDelta.y);
inputVector = new Vector2(pos.x * 2 - 1, pos.y * 2 - 1);
inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;
// Di chuyển handle của joystick
joystickHandle.rectTransform.anchoredPosition = new Vector2(inputVector.x * (joystickBackground.rectTransform.sizeDelta.x / 2.5f),
inputVector.y * (joystickBackground.rectTransform.sizeDelta.y / 2.5f));
}
}
public void OnPointerUp(PointerEventData eventData)
{
inputVector = Vector2.zero;
joystickHandle.rectTransform.anchoredPosition = Vector2.zero;
}
}Tạo một joystick ảo có thể di chuyển bằng cách kéo thả trên màn hình cảm ứng. Yêu cầu 2 đối tượng Image UI cho background và handle của joystick.