0
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 1 year has passed since last update.

[Unity]オブジェクトをフリック操作で飛ばす方法

Posted at

今回は3D空間でフリック操作でオブジェクトを飛ばす実装についてです!

使用PC: MacBook Pro (13-inch, M1, 2020)
OSバージョン: 11.5.2
Unityバージョン:2021.3.2f1

実際にプレイすると

フリック最終_AdobeExpress.gif

unityの設定

サンプルの動画では
①Plane
②Cube
③Material(赤色)→Cubeにつける
をアセットとして使用しています。

CubeにはRigidbodyをAdd Componentしています。

コード全文

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FlickScript : MonoBehaviour
{
    public float powerPerPixel;
    public float maxPower;
    Vector3 touchPos;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            touchPos = Input.mousePosition;
        }else if (Input.GetMouseButtonUp(0))
        {
            Vector3 releasePos = Input.mousePosition;
            float swipeDistanceY = releasePos.y - touchPos.y;
            float powerY = swipeDistanceY * powerPerPixel;
            float swipeDistanceX = releasePos.x - touchPos.x;
            float powerX = swipeDistanceX * powerPerPixel;

            if (powerX < 0)
            {
                powerX *= -1;
            }
            if (powerY < 0)
            {
                powerY *= -1;
            }

            if( powerX > maxPower)
            {
                powerX = maxPower;
            }
            if (powerY > maxPower)
            {
                powerY = maxPower;
            }

            GetComponent<Rigidbody>().AddForce(new Vector3(powerX * swipeDistanceX, 0, powerY * swipeDistanceY), ForceMode.Impulse);
        }
    }
}

Cubeにスクリプトを貼り付けします。

以上

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?