動くプレイヤー(ターゲット)の方向を向き続けるGameObjectの作り方です。
Quaternion.LookRotationを使います。
プレイヤーとしては以下を使います。
完成動作
作り方(動画)
作り方(ブログ)
1.シーンに各オブジェクトを配置
1-1.以下のようにunity-chan(今回はこれをプレイヤー)とBase(赤いCylinder)とNozzle(青いCylinder)を設置する。Baseが親、Nozzleが子のオブジェクトとなるようにする。
※今回はNozzleがunity-chanの方を向き続けるようにする。この後のスクリプトの便宜上、Nozzleは先端がZ軸を向くようにする。
流れとしてはBaseをスクリプトでプレイヤーの方向に回転させて、子であるNozzleも回転する仕組み

2.プレイヤー(ターゲット)の方向を向き続けるスクリプトを作成
2-1.LockRotation.csという名前のスクリプトを作成して、以下のコードを記載する。
using UnityEngine;
public class LockRotation : MonoBehaviour
{
[SerializeField]
[Tooltip("対象物(向く方向)")]
private GameObject target;
private void Update()
{
// 対象物と自分自身の座標からベクトルを算出
Vector3 vector3 = target.transform.position - this.transform.position;
// もし上下方向の回転はしない(Baseオブジェクトが床から離れないようにする)ようにしたければ以下のようにする。
// vector3.y = 0f;
// Quaternion(回転値)を取得
Quaternion quaternion = Quaternion.LookRotation(vector3);
// 算出した回転値をこのゲームオブジェクトのrotationに代入
this.transform.rotation = quaternion;
}
}
3.スクリプトをアタッチ
3-1.LockRotationスクリプトをプレイヤー(ターゲット)の方向を向き続けさせたいGameObject(今回はBaseオブジェクト)にアタッチ


4.LockRotationスクリプトのプロパティの設定
4-1.LockRotationスクリプトのTargetプロパティにプレイヤー(ターゲット)を設定(今回はunity-chan)


完成
これでゲームをスタートしてプレイヤーが動くと、Baseが回転して、その子であるNozzleもプレイヤーの方を向き続ける。
コメント