개발일기
정해진 경로 설정 본문
1. WayPoint
앞에서 생성한 타일에 삽입할 WayPoint Script를 작성합니다.
public class WayPoint : MonoBehaviour
{
[SerializeField] Tower towerPrefab;
[SerializeField] bool isPlaceable;
public bool IsPlaceable { get { return isPlaceable; } set { isPlaceable = value; } }
void OnMouseDown()
{
if (isPlaceable)
{
bool isPlaced = towerPrefab.CreateTower(towerPrefab, transform.position);
isPlaceable = isPlaced;
}
}
}
- 길 타일에는 isPlaceable를 false로 기본 타일에는 true로 설정하여 타워를 세울 수 있게 했습니다.
- 타워를 세울 수 있는 돈이 있다면 OnMouseDown 메서드를 실행하고, isPlaceable이 true라면 타워를 세웁니다.
- WayPoint는 타일의 종류와 상관없이 모든 타일의 컴포넌트로 삽입되어 있으며, 경로를 찾을 때 사용하게 됩니다.
2. 경로 설정
지금까지 생성한 타일들을 맵에 배치하고 게임 오브젝트를 생성하여 다음과 같이 분류해줍니다.
경로를 찾는 방식은 Path Tag를 가진 오브젝트를 찾고, 그 오브젝트의 자식 오브젝트에 삽입된 WayPoint를 순서대로 받아오는 방식이기에 오브젝트의 순서를 잘 정렬해야 합니다.

WayPoint를 이용해서 경로를 설정하는 EnemyMover Script입니다.
[RequireComponent(typeof(Enemy))]
public class EnemyMover : MonoBehaviour
{
[SerializeField] List<WayPoint> path= new List<WayPoint>();
[SerializeField] [Range(0f,5f)] float speed = 1f;
Enemy enemy;
void OnEnable()
{
FindPath();
ReturnToStart();
StartCoroutine(FollowPath());
}
void Start()
{
enemy = GetComponent<Enemy>();
}
void FindPath()
{
path.Clear();
GameObject parent = GameObject.FindGameObjectWithTag("Path");
foreach(Transform child in parent.transform)
{
WayPoint wayPoint = child.GetComponent<WayPoint>();
if(wayPoint!=null)
{
path.Add(wayPoint);
}
}
}
void ReturnToStart()
{
transform.position = path[0].transform.position;
}
IEnumerator FollowPath()
{
foreach(WayPoint wayPoint in path)
{
Vector3 startPos = transform.position;
Vector3 endPos = wayPoint.transform.position;
float travelPercent = 0f;
transform.LookAt(endPos);
while(travelPercent<1f)
{
travelPercent += Time.deltaTime * speed;
transform.position = Vector3.Lerp(startPos, endPos, travelPercent);
yield return new WaitForEndOfFrame();
}
}
FinishPath();
}
void FinishPath()
{
enemy.StealGold();
gameObject.SetActive(false);
}
}
- 전에 분류한 Path Object에만 Path란 Tag를 붙여주고 Path Obejct를 찾습니다.
- 그리고 해당 오브젝트의 자식들은 길 타일들이기 때문에 자식 오브젝트들의 WayPoint를 List에 삽입합니다.
- 코루틴 FollowPath를 실행해서 List에 담긴 WayPoint들의 오브젝트 위치로 이동시킵니다.
- 코루틴이 실행이 끝날 때까지 파괴되지 않았다는 것은 끝에 도달했다는 것이기에 FinishPath를 실행해서 패널티를 줍니다.
'Unity ToyProject > Defence' 카테고리의 다른 글
Toy Defence 완성 (0) | 2023.08.09 |
---|---|
BFS로 경로 찾기 (0) | 2023.08.08 |
BFS 알고리즘 (0) | 2023.08.07 |
좌표 설정 (0) | 2023.08.05 |
Grid Snapping (0) | 2023.08.04 |