Help us understand the problem. What is going on with this article?

フリック方向の判定 (unity)

前提

  • unity 2017.4、2018.4

できること

  • 二点の変位から上下左右を判定して返します。

コード

/// <summary>二点の位置から閾値を超えた4方位を算出する</summary>
public static Vector2Int GetDir (Vector2 currentPosition, Vector2 lastPosition, float threshold, Vector2 dpi = default (Vector2)) {
    var delta = (currentPosition - lastPosition) / ((dpi == default (Vector2)) ? new Vector2 (Screen.dpi, Screen.dpi) : dpi);
    var adx = Mathf.Abs (delta.x);
    var ady = Mathf.Abs (delta.y);
    var dir = Vector2Int.zero;
    if (adx > threshold || ady > threshold) {
        dir = (adx > ady) ?
            ((delta.x < 0) ? Vector2Int.left : Vector2Int.right) :
            ((delta.y < 0) ? Vector2Int.down : Vector2Int.up);
    }
    return dir;
}

使い方

  • 新しい位置、以前の位置、閾値、解像度(省略すると画面解像度)を渡します。
  • 閾値を超えたら、Vector2Int.leftVector2Int.rightVector2Int.downVector2Int.upのいずれかを返します。
  • 閾値を超えなければ、Vector2Int.zeroを返します。

var position = (Vector2) Input.mousePosition;
var dir = GetDir (position, lastPosition, FlickThreshold);
if (dir != Vector2Int.zero) {
    // フリックを検出
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away