상세 컨텐츠

본문 제목

유니티 그리드 시스템 적 움직이기

유니티/기능

by MJ_119 2024. 9. 4. 12:24

본문

그리드 시스템에서 적 한칸 한칸 움직이기

 

기초 

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

public class EnemyMover : MonoBehaviour
{
    [SerializeField] List<WayPoint> path = new List<WayPoint>();

    void Start()
    {
        StartCoroutine(PrintWayPointName());
    }

    IEnumerator PrintWayPointName()
    {
        foreach (WayPoint wayPoint in path)
        {
            print(wayPoint.name);
            transform.position = wayPoint.transform.position;
            yield return new WaitForSeconds(1);
        }
    }
}

 

 

 

 

 

 

@ 길을 따라 천천히 부드럽게 선형적으로 움직이기

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

public class EnemyMover : MonoBehaviour
{
    [SerializeField] List<WayPoint> path = new List<WayPoint>();
    [SerializeField] [Range(0,5f)] float speed = 1f;

    

    void Start()
    {
        StartCoroutine(PrintWayPointName());
    }

    IEnumerator PrintWayPointName()
    {
        foreach (WayPoint wayPoint in path)
        {
            Vector3 startPosition = transform.position;
            Vector3 endPosition = wayPoint.transform.position;

            // linearTime 초기화
            float linearTime = 0f;

            // 다음 길을 향해 바라보기
            transform.LookAt(endPosition);

            // 한칸씩 선형적으로 이동.
            while(linearTime < 1f)
            {
                linearTime += Time.deltaTime * speed;
                transform.position = Vector3.Lerp(startPosition, endPosition, linearTime);
                yield return new WaitForEndOfFrame();
            }
        }
    }
}

관련글 더보기