I am new to Unity and I am trying to make a swipe input for mobile using the Input.touch[0]
. I am getting the point touched and I'm using it to calculate the swipe delta, but the problem is the input coordinates are from the left corner of the screen. I need 0,0 from the center of the screen. This is my script:
public class SwipeController : MonoBehaviour
{
private bool tap, swipeLeft, swipeRight, swipeUp, swipeDown;
private bool isDragging;
private Vector2 startTouch, swipeDelta;
private void Update()
{
tap = swipeLeft = swipeRight = swipeUp = swipeDown = false;
//stand Alone Inputs
if (Input.GetMouseButtonDown(0))
{
isDragging = true;
tap = true;
startTouch = Input.mousePosition;
} else if (Input.GetMouseButtonUp(0)) {
isDragging = false;
Reset();
}
//MOBILE INPUTS
if (Input.touches.Length > 0 )
{
if(Input.touches[0].phase == TouchPhase.Began)
{
tap = true;
isDragging = true;
startTouch = Input.touches[0].position;
} else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
{
isDragging = false;
Reset();
}
}
//Distance calcs
if (isDragging)
{
if(Input.touches.Length > 0)
{
swipeDelta = Input.touches[0].position - startTouch;
} else if (Input.GetMouseButton(0)) {
swipeDelta = (Vector2)Input.mousePosition - startTouch;
}
//DEAD ZONE?
if (swipeDelta.magnitude > 100)
{
float x = swipeDelta.x;
float y = swipeDelta.y;
if (Mathf.Abs(x) > Mathf.Abs(y))
{
//left or right
if (x < 0)
{
swipeLeft = true;
} else
{
swipeRight = true;
}
} else
{
// top or bottom
if (y < 0 )
{
swipeDown = true;
} else
{
swipeUp = true;
}
}
Reset();
}
}
}
private void Reset()
{
startTouch = swipeDelta = Vector2.zero;
}
public Vector2 SwipeDelta { get { return swipeDelta; } }
public bool SwipeLeft { get { return swipeLeft; } }
public bool SwipeRight { get { return swipeRight; } }
public bool SwipeUp { get { return swipeUp; } }
public bool SwipeDown { get { return swipeDown; } }
}
What am I missing?