nightward/Assets/Scripts/AttachToGameObject/BackGroundFitter.cs

56 lines
1.6 KiB
C#

using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
[ExecuteInEditMode]
public class BackgroundFitter : MonoBehaviour
{
#if UNITY_EDITOR
public bool SetFit = false;
private void Update()
{
if (SetFit)
{
SetFit = false;
Set();
}
}
#endif
public void Set()
{
//SpriteRenderer sr = GetComponent<SpriteRenderer>();
//if (sr.sprite == null) return;
//// 스프라이트의 원래 크기(픽셀 단위)
//float spriteWidth = sr.sprite.bounds.size.x;
//float spriteHeight = sr.sprite.bounds.size.y;
//// 카메라
//Camera cam = Camera.main;
//float worldScreenHeight = cam.orthographicSize * 2f; // 세로 크기(월드 단위)
//float worldScreenWidth = worldScreenHeight * cam.aspect; // 가로 크기(월드 단위)
//// 배경 스케일 계산
//transform.localScale = new Vector3(
// worldScreenWidth / spriteWidth,
// worldScreenHeight / spriteHeight,
// 1f
//);
var sr = GetComponent<SpriteRenderer>();
if (sr == null) return;
// 스프라이트 크기
float width = sr.sprite.bounds.size.x;
float height = sr.sprite.bounds.size.y;
// 화면 비율
float worldScreenHeight = Camera.main.orthographicSize * 2f;
float worldScreenWidth = worldScreenHeight * Screen.width / Screen.height;
// 꽉 차게 하기 (잘림 허용)
float scale = Mathf.Max(worldScreenWidth / width, worldScreenHeight / height);
transform.localScale = new Vector3(scale, scale, 1);
}
}