- Home /
2d swipe control not working.
Hey, I've been making a game and the last thing I needed to do was the swipe controls, I thought it was going to be easy because unity will have something implemented for us, but no, It is way harder than I thought so I had to follow a tutorial. what ended up happening is that my code isn't working, but I know the tutorial is good just that there is a problem in the code I wrote from the video (the video didn't have a copy of the code linked). What my code looks like now:
private bool tap, swipeLeft, swipeRight, swipeUp, swipeDown, isDraging;
private Vector2 startTouch, swipeDelta;
private float moveSpeed = 1.5f;
private void Update()
{
tap = swipeLeft = swipeRight = swipeUp = swipeDown = isDraging = false;
#region Standalone Input
//click
if (Input.GetMouseButtonDown(0))
{
tap = true;
isDraging = true;
startTouch = Input.mousePosition;
}
//release
else if (Input.GetMouseButtonUp(0))
{
isDraging = false;
Reset();
}
#endregion
#region Moblie Inputs
if(Input.touches.Length > 0)
{
if(Input.touches[0].phase == TouchPhase.Began)
{
isDraging = true;
tap = true;
startTouch = Input.touches[0].position;
}
else if(Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
{
isDraging = false;
Reset();
}
}
#endregion
#region Swipe Check
swipeDelta = Vector2.zero;
if (isDraging)
{
if (Input.touches.Length > 0)
{
swipeDelta = Input.touches[0].position - startTouch;
}
else if (Input.GetMouseButton(0))
{
swipeDelta = new Vector2(Input.mousePosition.x, Input.mousePosition.y) - startTouch;
}
}
Debug.Log(swipeDelta);
if (swipeDelta.magnitude > 125)
{
//which direction are we swiping in
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
{
//up or down
if(y < 0)
{
swipeDown = true;
}
else
{
swipeUp = true;
}
}
Reset();
}
#endregion
the swipeDelta is always 0.0, 0.0. The startTouch is working fine and showing the position of the click. I have no idea what could be wrong here, I've checked the code a few times now, haven't found anything suspicious yet.
Answer by Devster2020 · Jul 01, 2021 at 03:03 PM
tap = swipeLeft = swipeRight = swipeUp = swipeDown = isDraging = false;
Using this at the start of the Update make the variable isDraging every frame to false.. so your code can't works correctly because swipeDelta will be always equals to Vector2.zero!
If I can recommend a good plugin to manage gestures, I recommend you use LeanTouch. I used it in all my games.. the management is pretty easy!
Oh my god thank you, It's such an easy fix and now I feel so stupid
And thank you for suggesting lean touch, as a newbie I didn't know about it, love you for all the help
If you need help, just tag me :D have a nice day!