今回は3D空間でフリック操作でオブジェクトを飛ばす実装についてです!
使用PC: MacBook Pro (13-inch, M1, 2020)
OSバージョン: 11.5.2
Unityバージョン:2021.3.2f1
実際にプレイすると
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にスクリプトを貼り付けします。