Last active
April 11, 2022 04:31
-
-
Save msawangwan/9590b6be6362fe078754459ed177d4ec to your computer and use it in GitHub Desktop.
[csharp][unity] simple swipe controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
In the original source, there are two unnecessary magnitude calculations, calculated | |
each frame. This isn't the most performant choice as to calculate magnitude one must divide | |
by the sqrRoot of the sum of each component squared, so | |
this may improve performance, however slight. | |
Also removed was a redundant calculation where the original author determined | |
delta x and y, once for checking if a swipe happened and once more to determine the sign. | |
Essentially, all these removed operations, were calculating the same thing, so all the redundant | |
calculations were removed and replcaed by: | |
Vector3 positionDelta = (Vector3) t.position - startPosition; | |
which then yields delta x and delta y via positionDelta.x and positionDelta.y respectively. | |
There are some other improvements made to this script not shown in this example as they do not pertain | |
directly to the improvement of the original source code. | |
Original source: https://dl.dropboxusercontent.com/u/97948256/SwipeDetctor.cs | |
*/ | |
using UnityEngine; | |
public class InputController : MonoBehaviour { | |
[SerializeField] private float minimumSwipeDistanceY; | |
[SerializeField] private float minimumSwipeDistanceX; | |
private Touch t = default(Touch); | |
private Vector3 startPosition = Vector3.zero; | |
private void Update () { | |
if (Input.touches.Length > 0) { | |
t = Input.touches[0]; | |
switch (t.phase) { | |
case TouchPhase.Began: | |
startPosition = t.position; | |
return; | |
case TouchPhase.Ended: | |
Vector3 positionDelta = (Vector3) t.position - startPosition; | |
if (Mathf.Abs(positionDelta.y) > minimumSwipeDistanceY) { | |
if (positionDelta.y > 0) { | |
Debug.Log("UP SWIPE!!!"); | |
} else { | |
Debug.Log("DOWN SWIPE!!!"); | |
} | |
} | |
if (Mathf.Abs(positionDelta.x) > minimumSwipeDistanceX) { | |
if (positionDelta.x > 0) { | |
Debug.Log("SWIPE RIGHT"); | |
} else { | |
Debug.Log("SWIPE LEFT"); | |
} | |
} | |
return; | |
default: | |
return; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment