공부 기록/유니티 Unity
[Unity/TIL] 장애물과 배경 반복 생성되게 하기
톰마토
2025. 2. 15. 20:10
728x90
장애물과 배경 반복 생성되게 하기
편하게 하기 위해 충돌 처리할건데, 그러기 위해 충돌체가 계속 따라오게 할거임.
근데 지금 플레이어를 계속 따라오는게 MainCamera니까 카메라 하위에 체크용 충돌체 하나 놓을거임!
=> BgLooper 라는 빈 오브젝트를 MainCamera에 달아줌
BgLooper가 닿으면 닿은 애가 저~~ 뒤에 생기게 하면 된다.
- "닿았냐"의 처리는 물리적 충돌이 필요한 것이 아니니까 Trigger 충돌로 확인할 것이다.
- Obstacle과 background 들에는 Box Collider 달아주고 IsTrigger 체크 해야 함.
BgLooper에 달아주는 스크립트
CompareTag로 background 트리거 처리, GetComponent로 Obstacle이 달려있는지 확인으로 장애물 트리거 처리
public class BgLooper : MonoBehaviour
{
public int numBgCount = 5;
public int obstacleCount = 0;
public Vector3 obstacleLastPosition = Vector3.zero;
// Start is called before the first frame update
void Start()
{
Obstacle[] obstacles = GameObject.FindObjectsOfType<Obstacle>(); // 이 씬에 존재하는 모든 오브젝트 돌아다니면서 Obstacle이 달려있는 지를 찾아옴
obstacleLastPosition = obstacles[0].transform.position;
obstacleCount = obstacles.Length;
for(int i = 0; i < obstacleCount; i++)
{
obstacleLastPosition = obstacles[i].SetRandomPlace(obstacleLastPosition, obstacleCount);
}
}
// 트리거 충돌은 진짜 충돌이 일어나는게 아니라서 Collision '충돌' 자체 정보가 아닌 충돌체의 정보만 줌.
private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("Triggered : " + collision.name);
// Tag로 backgound 트리거 처리
if(collision.CompareTag("BackGround"))
{
float widthOfBgObject = ((BoxCollider2D)collision).size.x;
Vector3 pos = collision.transform.position;
pos.x += widthOfBgObject * numBgCount;
collision.transform.position = pos;
return;
}
// GetComponent로 Obstacle 트리거 처리
Obstacle obstacle = collision.GetComponent<Obstacle>();
if(obstacle)
{
obstacleLastPosition = obstacle.SetRandomPlace(obstacleLastPosition, obstacleCount);
}
}
}
결과물
728x90