-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBackgroundScaler.cs
55 lines (44 loc) · 1.82 KB
/
BackgroundScaler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Resharper disable all
// **************************************************************** //
//
// Copyright (c) RimuruDev. All rights reserved.
// Contact me:
// - Gmail: rimuru.dev@gmail.com
// - GitHub: https://github.com/RimuruDev
// - LinkedIn: https://www.linkedin.com/in/rimuru/
// - GitHub Organizations: https://github.com/Rimuru-Dev
// - Gists: https://gist.github.com/RimuruDev/61e9f0111b35d3e67ef18fab611d7595
// **************************************************************** //
using UnityEngine;
namespace RimuruDev
{
[SelectionBase]
[DisallowMultipleComponent]
[RequireComponent(typeof(SpriteRenderer))]
[HelpURL("https://github.com/RimuruDev/Unity-BackgroundScaler")]
public sealed class BackgroundScaler : MonoBehaviour
{
[SerializeField] private Camera cameraRenderer;
private SpriteRenderer backgroundSpriteRenderer;
private void Awake() =>
backgroundSpriteRenderer = GetComponent<SpriteRenderer>();
private void Start() =>
ScaleBackground();
private void LateUpdate() =>
ScaleBackground();
private void ScaleBackground()
{
var targetHeight = cameraRenderer.orthographicSize * 2;
var targetWidth = targetHeight * Screen.width / Screen.height;
var backgroundSize = backgroundSpriteRenderer.sprite.bounds.size;
var targetScale = Vector3.one;
var widthRatio = targetWidth / backgroundSize.x;
var heightRatio = targetHeight / backgroundSize.y;
if (widthRatio > heightRatio)
targetScale *= widthRatio;
else
targetScale *= heightRatio;
transform.localScale = targetScale;
}
}
}