0
2

More than 1 year has passed since last update.

【Unity】OnDrag関数でピンチ処理を作る

Posted at

実装

using System;
using UnityEngine;
using UnityEngine.EventSystems;

public class PinchControl : MonoBehaviour, IDragHandler, IBeginDragHandler
{
    public event Action<float> OnPinchDelta = delegate { };

    private float prePinchInterval = float.NegativeInfinity;

    public void OnBeginDrag(PointerEventData data)
    {
        prePinchInterval = float.NegativeInfinity;
    }

    public void OnDrag(PointerEventData data)
    {
        if (Input.touchCount < 2)
        {
            prePinchInterval = float.NegativeInfinity;
        }
        else
        {
            var interval = Vector2.Distance(Input.GetTouch(0).position, Input.GetTouch(1).position);
            if (float.IsInfinity(prePinchInterval)) prePinchInterval = interval;
            OnPinchDelta(interval / prePinchInterval);
            prePinchInterval = interval;
        }
    }
}

OnDrag関数で2つのタッチ座標から距離を取得し、前フレームとの差を使用します。

前フレームとの差はだいたい 0.9 ~ 1.1 になるので使うスクリプトで乗算しましょう。

サンプル

using UnityEngine;

public class Sample : MonoBehaviour
{
    [SerializeField] private PinchControl pinch;

    public void OnEnable()
    {
        pinch.OnPinchDelta += OnPinch;
    }

    public void OnDisable()
    {
        pinch.OnPinchDelta -= OnPinch;
    }

    private void OnPinch(float scale)
    {
        transform.localScale *= scale;
    }
}

モバイル端末にビルドして動作確認をすると、Raycastに反応するuGUIでピンチイン・ピンチアウトができるようになります。

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