I’m trying to script a basic camera controller that pans the top-down camera as the user swipes the screen. I’ve almost got it working, but I have run into a weird issue. When swiping up or down, the camera reacts correctly, and moves up or down, however when swiping left or right the camera always moves ONLY right.
I’ve been staring at my script for hours and cannot figure out how this is possible.
Here is the snippet of my script in question (some variables are defined above this area of the script, so dont worry about stuff like that) , I coded it for left/right swipes exactly as for up/down, but it refuses to work correctly.
@Straafe, This is what I came up with to detect only horizontal and vertical swipes not diagonal. I hope it helps you achieve what you want and others.
using UnityEngine;
public class SwipeInput : MonoBehaviour
{
public bool swiping;
public float minSwipeDistance;
public float errorRange;
public SwipeDirection direction = SwipeDirection.None;
public enum SwipeDirection {Right, Left, Up, Down, None}
private Touch initialTouch;
void Start()
{
Input.multiTouchEnabled = true;
}
void Update()
{
if (Input.touchCount <= 0)
return;
foreach (var touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
initialTouch = touch;
}
else if (touch.phase == TouchPhase.Moved)
{
var deltaX = touch.position.x - initialTouch.position.x; //greater than 0 is right and less than zero is left
var deltaY = touch.position.y - initialTouch.position.y; //greater than 0 is up and less than zero is down
var swipeDistance = Mathf.Abs(deltaX) + Mathf.Abs(deltaY);
if (swipeDistance > minSwipeDistance && (Mathf.Abs(deltaX) > 0 || Mathf.Abs(deltaY) > 0))
{
swiping = true;
CalculateSwipeDirection(deltaX, deltaY);
}
}
else if (touch.phase == TouchPhase.Ended)
{
initialTouch = new Touch();
swiping = false;
direction = SwipeDirection.None;
}
else if (touch.phase == TouchPhase.Canceled)
{
initialTouch = new Touch();
swiping = false;
direction = SwipeDirection.None;
}
}
}
void CalculateSwipeDirection(float deltaX, float deltaY)
{
bool isHorizontalSwipe = Mathf.Abs(deltaX) > Mathf.Abs(deltaY);
// horizontal swipe
if (isHorizontalSwipe && Mathf.Abs(deltaY) <= errorRange)
{
//right
if (deltaX > 0)
direction = SwipeDirection.Right;
//left
else if (deltaX < 0)
direction = SwipeDirection.Left;
}
//vertical swipe
else if (!isHorizontalSwipe && Mathf.Abs(deltaX) <= errorRange)
{
//up
if (deltaY > 0)
direction = SwipeDirection.Up;
//down
else if (deltaY < 0)
direction = SwipeDirection.Down;
}
//diagonal swipe
else
{
swiping = false;
}
}
}
Hi guys, I wrote this simple tutorial wich is basically 7 lines of code and works like a charm. Easy and simple. You just have to use te build in Unity event system instead to write long and useless code. No need to use an update or fixed update.