using UnityEngine; // 왼쪽 끝으로 이동한 배경을 오른쪽 끝으로 재배치하는 스크립트 public class BackgroundLoop : MonoBehaviour { public Sprite[] backgroundSprites; // 순서대로 교체할 공항 배경 스프라이트 public int startSpriteIndex = 0; // 이 배경 오브젝트가 시작할 스프라이트 번호 public int spriteAdvanceOnLoop = 2; // 배경 오브젝트가 두 장이므로 재배치될 때 두 칸씩 진행 private float width; // 배경의 가로 길이 private int currentSpriteIndex; // 현재 표시 중인 스프라이트 번호 private SpriteRenderer spriteRenderer; // 배경을 표시하는 스프라이트 렌더러 private void Awake() { // 가로 길이를 측정하는 처리 BoxCollider2D backgroundCollider = GetComponent(); width = backgroundCollider.size.x; spriteRenderer = GetComponent(); currentSpriteIndex = NormalizeSpriteIndex(startSpriteIndex); ApplyBackgroundSprite(currentSpriteIndex); } private void Update() { // 현재 위치가 원점에서 왼쪽으로 width 이상 이동했을때 위치를 리셋 if(transform.position.x <= -width) { Reposition(); } } // 위치를 리셋하는 메서드 private void Reposition() { Vector2 offset = new Vector2(width * 2f, 0); transform.position = (Vector2) transform.position + offset; currentSpriteIndex = NormalizeSpriteIndex(currentSpriteIndex + spriteAdvanceOnLoop); ApplyBackgroundSprite(currentSpriteIndex); } private int NormalizeSpriteIndex(int index) { if(backgroundSprites == null || backgroundSprites.Length == 0) { return 0; } int normalizedIndex = index % backgroundSprites.Length; if(normalizedIndex < 0) { normalizedIndex += backgroundSprites.Length; } return normalizedIndex; } private void ApplyBackgroundSprite(int index) { if(spriteRenderer == null || backgroundSprites == null || backgroundSprites.Length == 0) { return; } Sprite backgroundSprite = backgroundSprites[index]; if(backgroundSprite != null) { spriteRenderer.sprite = backgroundSprite; } } }