Hello everyone, I hope someone can help me figure this out. I have this script that I’m using to create an on-screen joystick the player can drag to move their character. The movement part works perfectly. The problem is that no matter where I put the joystick and pad UI elements, the ‘center’ of the joystick pad always defaults to the bottom left corner of my UI canvas. Such that the only want to actually drag the joystick down or to the left is to move the cursor off-screen. This is not ideal, as the game is a phone app and you can’t just drag your finger off the screen.
I can’t seem to figure out where in here or the object settings that the center area is being off-set.
Any help would be greatly appreciated.
Here’s the code I’m using.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Joystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
public Transform player;
Vector2 move;
public float moveSpeed;
public RectTransform pad;
public void OnDrag(PointerEventData eventData)
{
transform.position = eventData.position;
transform.localPosition =
Vector2.ClampMagnitude(eventData.position - (Vector2)pad.position, pad.rect.width * 0.3f);
move = new Vector2(transform.localPosition.x, transform.localPosition.y).normalized;
}
public void OnPointerUp(PointerEventData eventData)
{
transform.localPosition = Vector2.zero;
move = Vector2.zero;
StopCoroutine("PlayerMove");
}
public void OnPointerDown(PointerEventData eventData)
{
StartCoroutine("PlayerMove");
}
IEnumerator PlayerMove()
{
while (true)
{
player.Translate(move * moveSpeed * Time.deltaTime, Space.World);
yield return null;
}
}
}