How do I implement swipe function to run?
Hello,
I need insight on a swipe function to run in either direction and a hold function that slows or increase the speed of the player. I have the most of the movement code done.
Here's the swipe code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Swipe : MonoBehaviour { private bool tap, swipeLeft, swipeRight, swipeUp, swipeDown; private Vector2 startTouch, swipeDelta; private bool isDragging = false; private object swipeDeltaVector2; private object returnswipeDelta;
private void Update()
{
tap = swipeLeft = swipeRight = swipeUp = swipeDown = false;
#region Standalone Inputs
if (Input.GetMouseButtonDown(0))
{
tap = true;
isDragging = true;
startTouch = Input.mousePosition;
}
else if(Input.GetMouseButtonUp(0))
{
isDragging = false;
Reset();
}
#endregion
#region Mobile Inputs
if(Input.touches.Length > 0)
{
if (Input.touches[0].phase == TouchPhase.Began)
{
isDragging = true;
tap = true;
startTouch = Input.touches[0].position;
}
else if(Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
{
isDragging = false;
Reset();
}
}
#endregion
//Caculated distance
swipeDelta = Vector2.zero;
if (isDragging)
{
if (Input.touches.Length > 0)
swipeDelta = Input.touches[0].position - startTouch;
else if (Input.GetMouseButton(0))
swipeDelta = (Vector2)Input.mousePosition - startTouch;
}
//deadzone
if(swipeDelta.magnitude > 125)
{
//Directions
float x = swipeDelta.x;
float y = swipeDelta.y;
if(Mathf.Abs(x) > Mathf.Abs(y))
{
//left or righ
if (x < 0)
swipeLeft = true;
else
swipeRight = true;
}
else
{
if (y < 0)
swipeDown = true;
else
swipeUp = true;
}
Reset();
}
}
private void Reset()
{
startTouch = swipeDelta = Vector2.zero;
isDragging = false;
}
public bool Tap { get { return tap; } }
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; } }
}
And here's the swipeTest: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class SwipeTest : MonoBehaviour { public Swipe swipeControls; public Transform player; private Vector3 desiredPosition;
private void Update()
{
if (swipeControls.SwipeLeft)
desiredPosition += Vector3.left;
if (swipeControls.SwipeRight)
desiredPosition += Vector3.right;
if (swipeControls.SwipeUp)
desiredPosition += Vector3.forward;
if (swipeControls.SwipeDown)
desiredPosition += Vector3.back;
player.transform.position = Vector3.MoveTowards(player.transform.position, desiredPosition, 3f * Time.deltaTime);
if (swipeControls.Tap)
Debug.Log("Tap!");
}
}