Unityにはタップは取得できるものの、フリック、スワイプが取得できないので実装
オブジェクトに以下のスクリプトをアタッチする
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
using UnityEngine; | |
using UnityEngine.UI; | |
using System.Collections; | |
public class TapAction : MonoBehaviour { | |
public float flickTime = 0.15f; //フリック判定用 時間しきい値 | |
public float flickMagnitude = 100; //フリック判定用 移動距離 | |
private Vector2 startPosition; //タップ開始ポイント | |
private Vector2 endPosition; //タップ終了ポイント | |
private float timer = 0.0f; //フリック判定用 タイマー | |
void Update() { | |
//タップ開始時 | |
if (Input.GetTouch(0).phase == TouchPhase.Began) { | |
//タップ開始ポイントを取得 | |
startPosition = Input.GetTouch(0).position; | |
} | |
//タップ終了時 | |
if (Input.GetTouch(0).phase == TouchPhase.Ended) { | |
//タップ終了ポイントを取得 | |
endPosition = Input.GetTouch(0).position; | |
//タップ開始~終了ポイントの距離 | |
Vector2 direction = endPosition - startPosition; | |
//距離が指定以上、タップ時間が指定以下の場合、フリックと判定 | |
if (direction.magnitude >= flickMagnitude && timer <= flickTime) { | |
//x軸の距離が大きい場合は左右へのフリック | |
if (Mathf.Abs(direction.x) >= Mathf.Abs(direction.y)) { | |
if (direction.x >= 0) { | |
//Right Flick | |
} | |
else { | |
//Left Flick | |
} | |
} | |
//y軸の距離が大きい場合は上下のフリック | |
else if (Mathf.Abs(direction.x) < Mathf.Abs(direction.y)) { | |
if (direction.y >= 0) { | |
//Up Flick | |
} | |
else { | |
//Down Flick | |
} | |
} | |
} | |
//タイマーを初期化 | |
timer = 0.0f; | |
} | |
//タップ中 | |
if (Input.GetTouch(0).phase == TouchPhase.Moved) { | |
//タップ時間がしきい値を越えた場合、スワイプと判定 | |
if (timer >= flickTime) { | |
//Swipe | |
} | |
//押下している間、タイマーを加算 | |
timer += Time.deltaTime; | |
} | |
} | |
} |
タップしてからの経過時間と離すまでの距離から、フリックとスワイプを判定している。
そのため、一定時間(0.15秒)が経過するまでスワイプ処理が始められないのが欠点。