Hi
I’m struggling a lot with moving my player with touch input.
What I’m trying to achieve is this.
If I move my finger 2 cm to the left, right, up or down on the phone, I want my Player GameObject to move the equivalent range in the same direction. Or at least a range defined by how many percent the finger has moved according to the “movement area”.
I’ve ran through the unity mobile space shooter tutorial and the movement script is not… the best
Even though I do appreciate it a whole lot.
Any help with this (pointers to tutorials or documentation) is greatly appreciated.
Movement Script so far (almost copy paste from Unity). I call GetDirection() in another script during FixedUpdate where I move the player GameObject accordingly to the direction. But it’s not as responsive as I would like it to be (at all):
using UnityEngine;
using UnityEngine.EventSystems;
public class MovementArea : MonoBehaviour, IPointerUpHandler, IDragHandler, IPointerDownHandler
{
public float Smoothing;
private Vector2 origin;
private Vector2 direction;
private Vector2 smoothDirection;
private bool touched;
private int pointerID;
public void OnPointerUp(PointerEventData eventData)
{
if (!touched)
{
touched = true;
pointerID = eventData.pointerId;
origin = eventData.position;
}
}
public void OnDrag(PointerEventData eventData)
{
if (eventData.pointerId == pointerID)
{
var currentPosition = eventData.position;
var directionRaw = currentPosition - origin;
direction = directionRaw.normalized;
}
}
public void OnPointerDown(PointerEventData eventData)
{
if (eventData.pointerId == pointerID)
{
touched = false;
direction = Vector2.zero;
}
}
public Vector2 GetDirection()
{
if (touched)
{
return Vector2.zero;
}
smoothDirection = Vector2.MoveTowards(smoothDirection, direction, Smoothing);
return smoothDirection;
}
}