目次
実装したいこと
動画のように前の車両に遅れてついていく電車を作成します
シューティングのサブ機とかにも使えそうですね
※今回の記事は自分へのメモ用ですので説明は割愛しています
ご了承下さい
事前準備
UniRXというライブラリを使用するので、AssetStoreにてUniRXを探し、ダウンロードします
スクリプト
using UnityEngine; using UniRx; using UniRx.Triggers; public class TrainDelayMove : MonoBehaviour { public Transform target; // 追従したい対象。とりあえずひとつ前の車両を想定 public float delay; // 動きの遅れ時間 private Vector3 _offsetPosition; // 追従先とのPosition差分。進行方向に従って更新が必要 private float _offsetDistance; // 追従先との距離差分。_offsetDistanceは基本的に不変 [SerializeField] float TrainAdjustHor; [SerializeField] float TrainAdjustVar; private void Start() { this.UpdateAsObservable() .Select(_ => (target.position, target.rotation)) .Delay(System.TimeSpan.FromSeconds(delay)) .Subscribe(target => { UpdateOffset(target.rotation); UpdatePosition(target.position); UpdateRotation(target.rotation); }) .AddTo(this); _offsetPosition = transform.position - target.position; _offsetDistance = _offsetPosition.magnitude; } /** * _offsetPositionの更新 */ void UpdateOffset(Quaternion delayedTarget) { Vector3 diffAngle = transform.rotation.eulerAngles - delayedTarget.eulerAngles; _offsetPosition = new Vector3(-Mathf.Sin(diffAngle.y), 0, Mathf.Cos(diffAngle.y)); } /** * 自身のpositionの更新 */ void UpdatePosition(Vector3 delayedTarget) { //transform.position = delayedTarget + _offsetPosition; transform.position = delayedTarget + transform.TransformDirection(Vector3.forward * TrainAdjustHor) + transform.TransformDirection(Vector3.up * TrainAdjustVar); } /** * 自身のrotationの更新 */ void UpdateRotation(Quaternion delayedTarget) { transform.rotation = delayedTarget; } }
各変数の設定
スクリプトは追従させたいオブジェクト(今回の場合は先頭車両に続く車両全て)にスクリプトをアタッチし、
- Target : 一つ前の車両をドラッグ&ドロップ
- delay : 遅延する時間
- TrainAdjustHor : 横軸のずれる量
- TrainAdjustVar : 縦軸のずれる量
コメント