【Unity】オブジェクトを周回させるスクリプト
目的
Unityでオブジェクトを周回させる方法についてメモする。今回は例としてキャラクタの周りをぐるぐる周回するSharkを作ってみます。
環境
Unity 2019 4.3f1
#NVJOB Boids
Standard Assetes
Step1 : 必要AssetのDownload&Import
今回は以下の二つのAssetを使用させてもらいます。Asset Storeから入手します。
- Standard Assets
- #NVJOB Boids
Standard Assetsは人型キャラクターを使うため、#NBJOB BoidsはSharkのprefabを使用するためです。
Step2 : オブジェクトの配置
まず初めにTerrianは何か適当に用意した後、Projectの中のAssetes > Standard Assets > Characters > ThirdPersonCharacter > ModelsからEthanのモデルをドラッグ&ドロップでSceneへ配置します。

次にSharkを配置します。Assetes > #NVJOB Boids >Example Scenes > Other > Shark >Mesh >SharkからSharkをドラッグ&ドロップで人型配置します。

Step3 : 周回スクリプトの作成
Project > Assetsの直下にC#スクリプトを作成し、以下のコードを記述します。以下の例ではスクリプト名をOrbitとしています。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Orbit : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField] GameObject center;
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.RotateAround(center.transform.position, Vector3.down, 20 * Time.deltaTime);
}
}
周回を制御するのはtransform.RotateAroundです。引数一つ目は周回の中心として設定するオブジェクトの座標です。今回はGameObjectから取得する設定にしています。引数二つ目が回転軸です。デフォルトだとY軸がUP方向なはずですので、Vector3.downでY軸方向に回転します。引数三つ目が回転速度です。速度調整はTime.deltaTimeの係数(上記だと20)を調整して変えてください。
Step4 : スクリプトのアタッチと中心設定
C#スクリプトをSharkに対してドラッグ&ドロップでアタッチした後、Inspecterから先ほどのOrbitスクリプトのCenterとして、人型キャラのEthanを設定します。

Step5 : 実行して確認
Gameを開始してみます。

無事にSharkがぐるぐる周回して狙われてる感がでました。
その他
途中でミスしたところとして、transform.RotateAroundでVector3.upとしていたらサメが後ろ向きに周回してしまいました。Vector3.downにすることで、前進してくれました。また、速度を-にすることでも同様に解消しました。このあたりはオブジェクトの配置の仕方にもよるので、動かして微調整というところです。
以上
Unityを一から学ぶのにおすすめの本はコチラ