티스토리 뷰
오늘 한 일 (회고)
오전
- 토끼 움직임 수정
- 스폰객체 호출 후 활성화 해제 할 때 함수가 다 끝나지 않아서 뜨던 오류 해결.
오후
- 팀프로젝트 진행
- 스폰존에 스폰객체가 뭉쳐서나오는 현상 수정
- 높낮이가 들쭉날쭉한 지형에 스폰존을 둘 시 navmesh 오류발견
새로 배운 것
Terrain을 이용하여 스폰위치 잡아주기
terrain은 지형을 의미합니다.
주로 넓은 땅이나 자연환경을 구성할 때 사용하는 요소입니다.
아래는 객체를 스폰할때 원래 쓰던 코드입니다.
public GameObject SpawnEnemies(Vector3 spawnLocation, PoolObject poolObject)
{
Vector3 randomOffset = new Vector3(Random.Range(-5, 5), 0, Random.Range(-5, 5));
Vector3 spawnPos = spawnLocation + randomOffset;
// 스폰 위치의 y 값 조절
if (Physics.Raycast(spawnPos + Vector3.up * 10, Vector3.down, out RaycastHit hitInfo, 20f))
{
spawnPos.y = hitInfo.point.y; // 바닥에 위치를 맞춤
}
else
{
spawnPos.y = spawnLocation.y; // 레이캐스트 실패 시 기본 위치
}
GameObject entity = GameManager.Instance.objectPool.GetFromPool(poolObject);
entity.transform.position = spawnPos;
entity.SetActive(true);
NavMeshAgent agent = entity.GetComponent<NavMeshAgent>();
if (agent != null && agent.isOnNavMesh)
{
agent.isStopped = false;
}
return entity;
}
레이로 스폰위치에서 10정도 올라와 아래방향으로 20f길이로 레이를 쏴줍니다
바닥을 맞춘다면 그 y위치에 객체를 놓아주는 방법을 사용했습니다.
하지만 몇몇객체들은 위치를 잡지 못하고 기본 위치에 가버려 navMesh에러가 떴습니다.
아래는 terrain을 이용한 방법입니다
public GameObject SpawnEnemies(Vector3 spawnLocation, PoolObject poolObject)
{
Vector3 randomOffset = new Vector3(Random.Range(-20, 20), 0, Random.Range(-20, 20));
Vector3 spawnPos = spawnLocation + randomOffset;
float groundHeight = terrain.SampleHeight(spawnPos) + terrain.transform.position.y;
spawnPos.y = groundHeight;
// Object Pool에서 좀비나 토끼 가져오기
GameObject entity = GameManager.Instance.objectPool.GetFromPool(poolObject);
entity.transform.position = spawnPos;
entity.SetActive(true);
NavMeshAgent agent = entity.GetComponent<NavMeshAgent>();
return entity;
}
terrain.SampleHeight( spawnPos )는
spawnPos의 위치에서 Terrain의 높이 위치에 맞게 변형해서 groundHeight에 초기화해줍니다.
spawnPos.y에 SampleHeight로 반환된 높이를 할당하면, spawnPos가 지형 위에 정확히 위치하게 됩니다