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

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

【Unity】線の上を移動する

前回オブジェクトを線でつなぎましたが 今回はその線の上を移動するプレーヤー(オブジェクト)を設定します
1.プレーヤーをシーン内にドラッグ&ドロップ
レイヤーの順序が0のためApartの下にあります

2.プレーヤにアニメーターとLineMoverというスクリプトを追加
アニメーターの追加方法はこちらをご覧ください
everydayisagoodday.hatenadiary.com
everydayisagoodday.hatenadiary.com

3.LineMoverスクリプトを編集

using UnityEngine;
public class LineMover : MonoBehaviour
{
    [SerializeField] LineRenderer line;
    [SerializeField] float speed = 1f;
    private Animator anim;
    private int currentIndex;

    private void Start()
    {
        anim = this.GetComponent<Animator>();
        currentIndex = 0;
        transform.position = line.GetPosition(currentIndex);
        GetComponent<SpriteRenderer>().sortingOrder += 3;
    }

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

        if (line.positionCount <= nextIndex)
        {
            return (line.GetPosition(currentIndex) + line.transform.position, true);
        }
        Vector3 nextPosition = line.GetPosition(nextIndex) + line.transform.position;

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

        if (distance < moveSpeed)
        {
            currentIndex += 1;
            return GetTargetPosition(moveSpeed - distance,nextPosition);
        }
        else
        {
            Vector3 direction = (nextPosition - currentPosition).normalized;
            return (currentPosition + direction * moveSpeed, false);
        }
    }
    private void Update()
    {
        var result = GetTargetPosition(speed * Time.deltaTime,transform.position);
        if (result.targetPosition.x>transform.position.x)
        {
            //右向き
            anim.SetFloat("X", 1f);
            anim.SetFloat("Y", 0);
        }
        else if (result.targetPosition.x < transform.position.x)
        {
            //左向き
            anim.SetFloat("X", -1f);
            anim.SetFloat("Y", 0);
        }
        else if (result.targetPosition.y > transform.position.y)
        {
            //後ろ向き
            anim.SetFloat("X", 0);
            anim.SetFloat("Y", 1f);
        }
        else
        {
            //前向き
            anim.SetFloat("X", 0);
            anim.SetFloat("Y", -1f);
        }
        transform.position = result.targetPosition;
        if (result.isEnd)
        {
            this.gameObject.SetActive(false);
        }
    }
}

4.LineMoverスクリプトにLineオブジェクトをドラッグ&ドロップ

これで実行すると線の上をプレーヤーが移動するようになります