Unity 타워디펜스 - 적이 길을 따라서 움직이게 하기

sh·2023년 12월 18일

일단 기능구현이 우선일 것 같아서 간단한 루트를 짰다

이런식으로.

파란색이 몬스터가 젠이 되는 위치. 그리고 빨간 점에 닿으면 사라진다.

꺾인 부분을 따라 적을 움직이게 하기 위해서는

이런식으로 Prefabs로 꺾이는 부분을 찍어주었다.
이렇게 찍은 점은 게임 화면에서는 안 보이고 그저 좌표를 저장하는 용도로만 사용된다.

그리고 각 좌표의 값과 현재 위치의 값을 빼서 그쪽으로 향하는 벡터를 생성.
그리고 transform을 변형시켜주었다.

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

public class EnemyMovement : MonoBehaviour
{
    public float speed = 3f;
    private Transform target;
    private int waypointIdx = 0;

    private void Start()
    {
        target = WayPoints.points[0];
    }

    private void Update()
    {
        Vector3 dir = target.position - transform.position;
        transform.Translate(dir.normalized * speed * Time.deltaTime, Space.World);

        if(Vector3.Distance(transform.position, target.position) <= 0.4f)
        {
            GetNextWayPoint();
        }
    }

    void GetNextWayPoint()
    {

        if(waypointIdx >= WayPoints.points.Length - 1)
        {
            Destroy(gameObject);
            return;
        }
        waypointIdx++;
        target = WayPoints.points[waypointIdx];


    }
}

0개의 댓글