今回はUnity2Dで簡単なルーレットを作成してみます。ボタンクリックでホイールを回転させて、止まった時の値を取得していきます。
はじめに
Unityのバージョンは2021.3.14f1です。
下記の画像を利用していきます、Inkscapeで簡単に作成したものです。

画像をAssetsフォルダ内に入れておきます。

実装開始
簡単な画面を作成した後にスクリプトで動きを実装します。利用する画像は上の画像だけです。
UI作成
シーンにwheel画像をドラッグアンドドロップします。

「2DObject」→「Sprites」→「Circle」を追加し、配下に「Triangle」を追加。

Triangleの位置とスケールを変更して、下記のような見た目にします。


スクリプトの作成
下記スクリプトを作成します。マウスを左クリックするとオブジェクトが回転して、徐々に回転が弱まって最後には止まります。
using UnityEngine; public class wheel : MonoBehaviour { private float speed; void Update() { if (Input.GetMouseButton(0)) speed = 20f; transform.Rotate(0, 0, speed); speed *= 0.98f; } }
スクリプトをwheelに追加します。

実行すると下記のようになります。

ランダム性の修正
次に「ランダム性」、「回転中の制御」と「矢印が示している数字の取得」を追加していきます。
Hierarchyで右クリックして「UI」→「Legacy」→「Button」を追加。

ButtonのRectTransform、Textを変更して下記のような感じにします。

スクリプトを下記に変更します。回転速度をランダムにし、止まった時に矢印が何処を示しているのかを「debug.log」で出力しています。また、回転中には再度回転しないようにフラグを追加しています。
using UnityEngine; public class wheel : MonoBehaviour { private float speed; private bool isRotate; private void Awake() { isRotate = false; } void Update() { if (isRotate) { transform.Rotate(0, 0, speed); speed *= 0.98f; if (speed <= 0.05f) { transform.Rotate(0, 0, 0); StopWheel(); isRotate = false; } } } public void Rotate() { if (!isRotate) { speed = Random.Range(10, 40); isRotate = true; } } private void StopWheel() { float rotz = transform.eulerAngles.z; if (rotz > 0 && rotz <= 90) Debug.Log("1"); if (rotz > 90 && rotz <= 180) Debug.Log("2"); if (rotz > 180 && rotz <= 270) Debug.Log("3"); if (rotz > 270 && rotz <= 360) Debug.Log("4"); } }
ボタンを押した時に回転させたいので下記のようにセットします。

実行すると下記のような感じに。コンソールに矢印に該当する値が出力されていたらOKです。
