Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Started work on joystick controls #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions Assets/VJHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class VJHandler : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
private Image jsContainer;
private Image joystick;

public Vector3 InputDirection;
// Start is called before the first frame update
void Start()
{
jsContainer = GetComponent<Image>();
joystick = transform.GetChild(0).GetComponent<Image>(); //this command is used because there is only one child in hierarchy
InputDirection = Vector3.zero;
}
public void OnDrag(PointerEventData ped)
{
Vector2 position = Vector2.zero;

//To get InputDirection
RectTransformUtility.ScreenPointToLocalPointInRectangle
(jsContainer.rectTransform,
ped.position,
ped.pressEventCamera,
out position);

position.x = (position.x / jsContainer.rectTransform.sizeDelta.x);
position.y = (position.y / jsContainer.rectTransform.sizeDelta.y);

float x = (jsContainer.rectTransform.pivot.x == 1f) ? position.x * 2 + 1 : position.x * 2 - 1;
float y = (jsContainer.rectTransform.pivot.y == 1f) ? position.y * 2 + 1 : position.y * 2 - 1;

InputDirection = new Vector3(x, y, 0);
InputDirection = (InputDirection.magnitude > 1) ? InputDirection.normalized : InputDirection;

//to define the area in which joystick can move around
joystick.rectTransform.anchoredPosition = new Vector3(InputDirection.x * (jsContainer.rectTransform.sizeDelta.x / 3)
, InputDirection.y * (jsContainer.rectTransform.sizeDelta.y) / 3);

}

public void OnPointerDown(PointerEventData ped)
{
OnDrag(ped);
}

public void OnPointerUp(PointerEventData eventData)
{
InputDirection = Vector3.zero;
joystick.rectTransform.anchoredPosition = Vector3.zero;
}
}