97 lines
2.9 KiB
Plaintext
97 lines
2.9 KiB
Plaintext
using UnityEngine;
|
|
using UnityEngine.EventSystems;
|
|
using UnityEngine.UI;
|
|
|
|
public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
|
|
{
|
|
public Image DragImage;
|
|
public RectTransform joystickBackground;
|
|
public RectTransform joystickHandle;
|
|
private Vector2 inputVector;
|
|
private Canvas canvas;
|
|
private bool isActive = false;
|
|
public bool m_click = false;
|
|
|
|
private void Start()
|
|
{
|
|
canvas = GetComponentInParent<Canvas>();
|
|
|
|
// Hide the joystick at the start
|
|
joystickBackground.gameObject.SetActive(false);
|
|
}
|
|
|
|
public void OnPointerDown(PointerEventData eventData)
|
|
{
|
|
m_click = true;
|
|
Vector2 position;
|
|
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
|
|
LayerMask mask = LayerMask.GetMask("MysticalScent");
|
|
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
|
|
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, eventData.position, eventData.pressEventCamera, out position))
|
|
{
|
|
// Activate and move the joystick to the click position
|
|
joystickBackground.anchoredPosition = position;
|
|
joystickBackground.gameObject.SetActive(true);
|
|
isActive = true;
|
|
|
|
OnDrag(eventData);
|
|
}
|
|
}
|
|
|
|
public void OnDrag(PointerEventData eventData)
|
|
{
|
|
if (!isActive) return;
|
|
|
|
Vector2 position;
|
|
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(joystickBackground, eventData.position, eventData.pressEventCamera, out position))
|
|
{
|
|
position.x = (position.x / joystickBackground.sizeDelta.x);
|
|
position.y = (position.y / joystickBackground.sizeDelta.y);
|
|
|
|
inputVector = new Vector2(position.x * 2, position.y * 2);
|
|
inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;
|
|
|
|
// Move Joystick Handle
|
|
joystickHandle.anchoredPosition = new Vector2(inputVector.x * (joystickBackground.sizeDelta.x / 2), inputVector.y * (joystickBackground.sizeDelta.y / 2));
|
|
}
|
|
}
|
|
|
|
public void OnPointerUp(PointerEventData eventData)
|
|
{
|
|
m_click = false;
|
|
inputVector = Vector2.zero;
|
|
joystickHandle.anchoredPosition = Vector2.zero;
|
|
|
|
// Hide the joystick when the touch is released
|
|
joystickBackground.gameObject.SetActive(false);
|
|
isActive = false;
|
|
}
|
|
|
|
public float Horizontal()
|
|
{
|
|
return inputVector.x;
|
|
}
|
|
|
|
public float Vertical()
|
|
{
|
|
return inputVector.y;
|
|
}
|
|
|
|
|
|
private PHomePlayer currPlayer;
|
|
|
|
public void SetPlayer(PHomePlayer player)
|
|
{
|
|
currPlayer = player;
|
|
}
|
|
|
|
void Update ()
|
|
{
|
|
if(currPlayer!=null)
|
|
{
|
|
currPlayer.Move(inputVector.normalized);
|
|
//currPlayer.Anim(inputVector.normalized);
|
|
}
|
|
}
|
|
}
|