4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UniRx 押した時と離れたときの間隔の短いタップを検出する

Last updated at Posted at 2020-07-25

概要

ポインターが押された時と離された時の間隔が一定以下のときだけ発火する物をUniRxで作成しました。

赤のエフェクトは押されたこと、青は離されたことを示します。その間隔が短いときだけLogが出力されてます。
shorttap.gif

プロジェクト全体はこちらから
https://github.com/Arihide/unirx-shorttap

説明

短いのでソースコード丸ごと乗っけます。

using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UniRx;
using UniRx.Triggers;

public class ShortTap : UIBehaviour
{
    protected override void Awake()
    {
        base.Awake();

        const double shortTapThreshold = 200d;

        this.OnPointerUpAsObservable()
            .Timestamp() // 時間情報付与
            .WithLatestFrom( // ポインターが離れたとき、最後に押された時の情報と合体させる
                this.OnPointerDownAsObservable().Timestamp(),
                (l, r) => new { up = l, down = r }
            )
            // 押した時と離れたときの間隔が shortTapThreshold 以下のときだけ通す
            .Where(pair => (pair.up.Timestamp - pair.down.Timestamp) <= TimeSpan.FromMilliseconds(shortTapThreshold))
            .Subscribe(_ => Debug.Log("Short Tap!"));
    }

}

やってることとしては、

  • ポインターが離れたときに、最後にポインターが押されたときの情報とニコイチにする
  • 押された時と離れたときの時刻を比較し、閾値以下なら通す
    という感じですね。

この方法は押されたときではなく、離れたときに発火するのがミソです。
また、条件式を調整すればロングタップなどにも対応できます。

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?