日々是好日~every day is a good day~

日常の中の非日常の備忘録

【Unity】任意の経路を移動する

以前オブジェクト間に線を描きその線上を移動する方法をアップしました
everydayisagoodday.hatenadiary.com
今回はその応用です
線の上ではなく 動かしたいところにポイントを置いてポイントを移動していきます
1.地図のイラストをシーン内にドラッグ&ドロップ

2.ヒエラルキーの+をクリックし空のオブジェクトを作成

3.名前をMovePointに変更 インスペクターの▼をクリックしてオブジェクトのアイコンを設定する

4.MovePointを右クリックし複製を選択 次に移動させたいポイントに位置を変更

5.これを移動させたいポイントの数だけ繰り返す

6.もう一度ヒエラルキーの+をクリックし空のオブジェクトを作成

7.名前をPointにしてMovePointをすべて子オブジェクトにする

8.移動させる画像をシーン内にドラッグ&ドロップし 名前をWalkerに変更する レイヤーの順序は1にする

9.WalkMapというスクリプトを作成し編集

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WalkMap : MonoBehaviour
{
    [SerializeField] GameObject point;
    [SerializeField] float speed = 1f;
    private Vector3[] movePoint;
    private int currentIndex;
    private int pointCount;
    private Vector3 direction;
    private bool isEnd = false;
   
    private void Start()
    {
        currentIndex = 0;
        pointCount = point.transform.childCount;
        movePoint = new Vector3[pointCount];
        for (int i=0;i<pointCount;i++)
        {
            movePoint[i] = point.transform.GetChild(i).transform.position;
        }
    }

    private Vector3 GetTargetPosition(float moveSpeed, Vector3 currentPosition)
    {
        int nextIndex = currentIndex + 1;

        if (pointCount == nextIndex)
        {
            isEnd = true;
            return (currentPosition);
        }
        Vector3 nextPosition = movePoint[nextIndex];

        float distance = Vector3.Distance(currentPosition, nextPosition);

        if (distance < moveSpeed)
        {
            currentIndex += 1;
            return GetTargetPosition(moveSpeed - distance, nextPosition);
        }
        else
        {
            direction = (nextPosition - currentPosition).normalized;
            return (currentPosition + direction * moveSpeed);
        }
    }
    private void Update()
    {
        if (!isEnd)
        {
            Vector3 targetPos = GetTargetPosition(speed * Time.deltaTime, transform.position);
            transform.rotation = Quaternion.FromToRotation(Vector3.up, direction);
            transform.position = targetPos;
        }
    }
}

10.WalkMapスクリプトをWalkerにアタッチ

11.WalkMapスクリプトにPointオブジェクトをドラッグ&ドロップ スピードは2にする

これで実行すると設定したポイントを移動するようになります