【Unity】ドラッグ(スワイプ)でオブジェクトを移動させる

マウスドラッグもしくはスマホのスワイプでオブジェクトを移動させるスクリプトを書きました。

Inputを使うと移動量が取れますので、移動量を使ってオブジェクトを移動させてあげます。

using UnityEngine;

public class InputGame : MonoBehaviour
{
    [SerializeField] GameObject target;
    [SerializeField] float mouse_sensitivity = 0.1f;
    [SerializeField] float touch_sensitivity = 0.001f;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        //ドラッグ中もしくはスワイプ中
        if (Input.GetMouseButton(0))
        {
            float dx,dy;

            //PCマウスの場合
            dx = Input.GetAxis("Mouse X") * mouse_sensitivity;
            dy = Input.GetAxis("Mouse Y") * mouse_sensitivity;

            //スマホのタッチの場合
            if (Input.touchCount > 0)
            {
                dx = Input.touches[0].deltaPosition.x * touch_sensitivity;
                dy = Input.touches[0].deltaPosition.y * touch_sensitivity;
            }

            //ドラッグした分だけオブジェクトを動かします。
            target.transform.Translate(dx, dy, 0.0f);
        }
    }
}

感度(sensitivity)を調節しないと、動きすぎたり、動かしづらかったりするのでその辺りは要注意です。

UnityRemote5を使って、スマホ(iPhoneX)でも動かしてみました。

タッチ操作の場合、オブジェクトが動きすぎたので、感度をマウスに比べてかなり小さい値にしています。

タブレットの画面サイズになると、また操作感が違ってくると思うので、感度は設定で調節できた方が親切ですね。

追記

Translateを使って移動させると、オブジェクトのすり抜けが発生してしまいました。

以下のようにFixed Updateの中でMovePositionを使って移動させるようにしました。

 private void FixedUpdate()
    {

        if (Input.GetMouseButton(0))
        {
            float dx, dy;

            dx = Input.GetAxis("Mouse X") * mouse_sensitivity * Time.deltaTime;
            dy = Input.GetAxis("Mouse Y") * mouse_sensitivity * Time.deltaTime;

            //スマホのタッチの場合
            if (Input.touchCount > 0)
            {
                Debug.Log("touch");
                dx = Input.touches[0].deltaPosition.x * touch_sensitivity * Time.deltaTime;
                dy = Input.touches[0].deltaPosition.y * touch_sensitivity * Time.deltaTime;
            }

            rb.MovePosition(rb.position + new Vector3(dx, dy, 0));
        }
    }

ABOUTこの記事をかいた人

個人アプリ開発者。Python、Swift、Unityのことを発信します。月間2.5万PVブログ運営。 Twitter:@yamagablog