LoginSignup
3
3

More than 5 years have passed since last update.

【Unity】スワイプ時のベクトルの取得方法

Last updated at Posted at 2019-05-13

概要

スワイプ時に指が画面上を移動した距離と方向(スワイプベクトルとここで呼ぶことにする)を取得する方法を書きました。

環境

Unity 2019 1.1f1
UniRx 6.2.2

コード

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniRx;
using UniRx.Triggers;

namespace Test
{
    public class MeasureSwipeVector : MonoBehaviour
    {
        //指が画面に触れた位置
        private Vector2 fingerDownPos;
        //指が画面から離れた位置
        private Vector2 fingerUpPos;
        //スワイプベクトル
        private Vector2 swipeVector;

        private void Start() {
            //マルチタッチを無効化
            Input.multiTouchEnabled = false;

            //指と画面が触れた位置を記録
            this.UpdateAsObservable()
                .Where(_ => Input.GetMouseButtonDown(0))
                .Subscribe(_ => fingerDownPos = Input.mousePosition);

            //指を離した位置を記録し、AmountOfMovementを計算
            this.UpdateAsObservable()
                .Where(_ => Input.GetMouseButtonUp(0))
                .Subscribe(_ => {
                    fingerUpPos = Input.mousePosition;
                    swipeVector = (fingerUpPos - fingerDownPos) / Screen.dpi;
                });
        }
    }
}

説明

Screen.dpiは1 PPI(1インチに含まれるピクセル数)を表します。
単位がpixelであるfingerUpPos - fingerDownPosScreen.dpiで割ることによって、単位がinchのスワイプベクトルswipeVectorを取得しています。

参考

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3