EerieVillage/Assets/Scripts/Background/LoopingBackdrop.cs

117 lines
5.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
namespace EerieVillage.Background
{
/// <summary>
/// 무한 가로 스크롤 배경 한 층(리뉴얼 2026-11-10 · PD 지시 「배경을 무한하게 스크롤 가능하게」).
/// <para>
/// 좌우 끝이 맞물리는 그림 1장을 화면 폭을 덮을 만큼 나란히 깔고, 카메라 가로 이동에 맞춰 감아 돌린다.
/// 텍스처는 1장만 쓰고(사본은 같은 Sprite 공유) 오브젝트 수는 화면 폭에 맞춰 최소로 만든다.
/// </para>
/// <para>
/// 크기·높이: <see cref="pixelsPerWorldUnit"/> &gt; 0 이면 「그림 px ÷ 월드 단위」 고정 배율로 키우고,
/// 그림 안 세로 위치 <see cref="anchorImageV"/>(아래 = 0) 를 월드 높이 <see cref="anchorWorldY"/> 에 맞춘다(그린 흙길 = 실제 땅).
/// 0 이하이면 화면 높이에 맞춰 키우고 화면에 붙어 다닌다.
/// </para>
/// </summary>
[RequireComponent(typeof(SpriteRenderer))]
public class LoopingBackdrop : MonoBehaviour
{
[Tooltip("화면에서 이 층이 지나가는 속도(땅 = 1). 0 = 화면에 고정, 0.3~0.5 = 먼 배경, 1 = 땅과 같이.")]
[Range(0f, 1f)] public float parallax = 0.4f;
[Header("고정 배율 · 땅 맞춤 (pixelsPerWorldUnit > 0)")]
[Tooltip("그림 px ÷ 월드 단위. 여러 층이 같은 값을 써야 그림이 맞물린다. 0 이하 = 화면 높이 맞춤 모드.")]
public float pixelsPerWorldUnit = 0f;
[Tooltip("그림 아래 끝 = 0, 위 끝 = 1 기준으로 땅(발 디딤선)이 그려진 세로 위치.")]
[Range(0f, 1f)] public float anchorImageV = 0.1f;
[Tooltip("그 디딤선을 맞출 월드 높이(실제 땅 윗면).")]
public float anchorWorldY = 0f;
[Tooltip("카메라 세로 이동을 따라가는 비율. 0 = 땅에 붙어 있음(권장), 1 = 화면에 붙어 다님.")]
[Range(0f, 1f)] public float verticalFollow = 0f;
[Header("화면 높이 맞춤 모드 (pixelsPerWorldUnit <= 0)")]
[Tooltip("화면 높이 대비 배경 높이 배율.")]
public float heightCoverage = 1.08f;
Camera _cam;
SpriteRenderer _sr;
Transform[] _tiles;
float _tileWidth, _height;
float _lastOrtho = -1f, _lastAspect = -1f;
Vector3 _camStart;
Vector3 _rootStart;
void Start()
{
_cam = Camera.main;
_sr = GetComponent<SpriteRenderer>();
if (_cam == null || _sr.sprite == null)
{
Debug.LogWarning($"[LoopingBackdrop@{name}] 카메라 또는 Sprite 없음 — 꺼짐.");
enabled = false;
return;
}
_camStart = _cam.transform.position;
_rootStart = transform.position;
Rebuild();
}
void Rebuild()
{
float viewH = _cam.orthographicSize * 2f;
float viewW = viewH * _cam.aspect;
Vector2 spriteSize = _sr.sprite.bounds.size;
_height = pixelsPerWorldUnit > 0f ? _sr.sprite.rect.height / pixelsPerWorldUnit : viewH * heightCoverage;
float scale = _height / spriteSize.y;
transform.localScale = new Vector3(scale, scale, 1f);
_tileWidth = spriteSize.x * scale;
int need = Mathf.CeilToInt(viewW / _tileWidth) + 2; // 화면 폭 + 양옆 여유 1장씩
if (_tiles != null) foreach (var t in _tiles) if (t != null && t != transform) Destroy(t.gameObject);
_tiles = new Transform[need];
_tiles[0] = transform;
for (int i = 1; i < need; i++)
{
var go = new GameObject($"{name}_Tile{i}");
go.transform.SetParent(transform, false);
go.transform.localPosition = new Vector3(i * spriteSize.x, 0f, 0f);
var sr = go.AddComponent<SpriteRenderer>();
sr.sprite = _sr.sprite;
sr.sortingLayerID = _sr.sortingLayerID;
sr.sortingOrder = _sr.sortingOrder;
sr.color = _sr.color;
sr.sharedMaterial = _sr.sharedMaterial;
_tiles[i] = go.transform;
}
_lastOrtho = _cam.orthographicSize;
_lastAspect = _cam.aspect;
}
void LateUpdate()
{
if (_cam == null) return;
if (!Mathf.Approximately(_lastOrtho, _cam.orthographicSize) || !Mathf.Approximately(_lastAspect, _cam.aspect)) Rebuild();
Vector3 cam = _cam.transform.position;
float viewW = _cam.orthographicSize * 2f * _cam.aspect;
// 가로: 이 층은 카메라 이동의 (1 - parallax) 배를 따라간다 → 화면에서는 땅 속도의 parallax 배로 지나간다.
float leftEdge = cam.x - viewW * 0.5f;
float baseX = _rootStart.x + (cam.x - _camStart.x) * (1f - parallax); // 감기 전 첫 장 가운데
float firstLeft = baseX - _tileWidth * 0.5f;
// 첫 장 왼쪽 끝이 화면 왼쪽 끝 바로 왼쪽(한 장 이내)에 오도록 타일 폭 단위로 감는다(그림이 좌우로 이어져 끊김 없음).
float k = Mathf.Floor((leftEdge - firstLeft) / _tileWidth);
float x = baseX + k * _tileWidth;
float y;
if (pixelsPerWorldUnit > 0f)
// 스프라이트 기준점 = 가운데 → 가운데 높이 = 디딤선 높이 + (0.5 - 디딤선 비율) × 높이
y = anchorWorldY + (0.5f - anchorImageV) * _height + (cam.y - _camStart.y) * verticalFollow;
else
y = cam.y;
transform.position = new Vector3(x, y, transform.position.z);
}
}
}