- Home /
How to make a touch joystick with PointerEventHandlers
I tried to implement a touch joystick which should activate on the place where the finger touches the screen. I only wanted to get the angle between the initial touch position and the current touch position, so that the player rotates according to that angle. But still I couldn't get the needed behavior properly. Any help on this case is highly valued.
The code is given below. Simply, when a mousedown happens, the pointer event data is taken as the center coordinates of the joystick ("start" variable in the code). When OnBeginDrag() is called, the angle between the centre (start) and the current position ("end" in the code) are taken to calculate the angle ("angle" variable in the code).
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class DragDetection : MonoBehaviour, IPointerDownHandler,IDragHandler, IEndDragHandler
{
public Transform start, end;
public float angle;
void countAngle(){
Debug.DrawLine(start.position,end.position);
Vector2 direction = start.position - end.position;
angle = Mathf.Atan2(direction.y,direction.x) * Mathf.Rad2Deg;
}
public virtual void OnPointerDown(PointerEventData eventData)
{
start.position = eventData.position;
end.position = eventData.position;
OnDrag(eventData);
}
public virtual void OnDrag(PointerEventData eventData)
{
end.position = eventData.position;
countAngle();
}
public virtual void OnEndDrag(PointerEventData eventData)
{
angle = 0f;
Debug.Log("END");
}
}
Your answer
Follow this Question
Related Questions
OnPointerExit Issue w/ Radial Menu on Android 1 Answer
Android Touch Issue(2 buttons) 0 Answers
Raycast from player to touch point? 2 Answers
Touch Input positions are different on iOS and Android? 2 Answers
Delta touch trembling 0 Answers