![見出し画像](https://assets.st-note.com/production/uploads/images/159548099/rectangle_large_type_2_1bdf07670097fbd564028595a629ffd9.png?width=1200)
Photo by
kentauroshappy
Unity オブジェクトをチェックポイントまで移動させるスクリプト
ChatGPTのおかげで、オブジェクトをチェックポイントまで移動するスクリプトが、すぐにできました。
こんなに楽していいのか…
自分で頑張って作ったスクリプトでないので、わざわざ投稿する必要ないですが、
今日の成果物ということで、載せておきます。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CheckpointMover : MonoBehaviour
{
// チェックポイントのリストをインスペクターで設定
public List<Transform> checkpoints;
public float speed = 5f; // 移動速度
private int currentCheckpointIndex = 0;
void Update()
{
// チェックポイントが設定されているか確認
if (checkpoints.Count == 0)
{
Debug.LogWarning("チェックポイントが設定されていません。");
return;
}
// 現在のチェックポイントまでの方向を計算
Transform targetCheckpoint = checkpoints[currentCheckpointIndex];
Vector3 direction = (targetCheckpoint.position - transform.position).normalized;
// オブジェクトを移動させる
transform.position += direction * speed * Time.deltaTime;
// チェックポイントに到達したか確認
if (Vector3.Distance(transform.position, targetCheckpoint.position) < 0.1f)
{
// 次のチェックポイントに進む
currentCheckpointIndex++;
// チェックポイントがリストの最後に到達したら停止またはループ
if (currentCheckpointIndex >= checkpoints.Count)
{
// ループさせたい場合
// currentCheckpointIndex = 0;
// 停止させたい場合
enabled = false;
}
}
}
}
1 複数のチェックポイント(空のGameObjectなど)を配置する。
2 移動するオブジェクトにアタッチする。
3 インスペクターの「Checkpoints」にチェックポイントをドラッグする。
これと「PLATEAU」で、いろいろなものを動かしてリアルな街を再現してみたいと思います。