- Home /
Do On swipe finger?
I am new in Unity, and i want to add 8 different functions on 8 type of swipe on the screen by finger. I found the code for 4 swipes (left right up and down) but i want to add 8 swipes this shown in image (just for example) .
#pragma strict
private var fp : Vector2; // first finger position
private var lp : Vector2; // last finger position
function Update () {
for (var touch : Touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
fp = touch.position;
lp = touch.position;
}
if (touch.phase == TouchPhase.Moved )
{
lp = touch.position;
}
if(touch.phase == TouchPhase.Ended)
{
if((fp.x - lp.x) > 80) // left swipe
{
transform.Rotate(0,180,0);
}
else if((fp.x - lp.x) < -80) // right swipe
{
transform.Rotate(0,40,0);
}
else if((fp.y - lp.y) < -80 ) // up swipe
{
// add your jumping code here
}
else if((fp.y - lp.y) < 80 ) // down swipe
{
// add your slip code here
}
}
}
}
Comment
Best Answer
Answer by robertbu · Aug 20, 2014 at 07:36 AM
Here is a bit of untested code. The value of 'which' passed to the switch statement start at 0 for directly right and walk around counter clockwise.
#pragma strict
private var fp : Vector2; // first finger position
function Update () {
for (var touch : Touch in Input.touches) {
if (touch.phase == TouchPhase.Began) {
fp = touch.position;
}
if(touch.phase == TouchPhase.Ended) {
if (fp == Input.mousePosition) return;
var dir = Input.mousePosition - fp;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
if (angle < 0.0)
angle = 360.0 + angle;
var which = Mathf.RoundToInt((angle) / 45.0);
which = which % 8;
switch(which) {
case 0:
Debug.Log("0");
break;
case 1:
Debug.Log("1");
break;
case 2:
Debug.Log("2");
break;
case 3:
Debug.Log("3");
break;
case 4:
Debug.Log("4");
break;
case 5:
Debug.Log("5");
break;
case 6:
Debug.Log("6");
break;
case 7:
Debug.Log("7");
break;
}
}
}
}