Untitled
unknown
csharp
2 years ago
2.9 kB
7
Indexable
Never
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ObjectScalerWithScreenSize : MonoBehaviour { public Vector2 actualObjectSize; public float SIZE_ON_SCREEN; public Text sizeText; public float screenHeight; public float screenWidth; void Start() { float frustumHeight = (Screen.height / Screen.dpi) * 2.54f; frustumHeight /= 100f; Debug.Log(Screen.dpi); Debug.Log(Screen.width + " " + Screen.height); Debug.Log((Screen.width / Screen.dpi) * 2.54f); Debug.Log((Screen.height / Screen.dpi) * 2.54f); var distance = frustumHeight * 0.5f / Mathf.Tan(Camera.main.fieldOfView * 0.5f * Mathf.Deg2Rad); screenHeight = (Screen.height / Screen.dpi) * 2.54f; screenHeight /= 100; screenWidth = (Screen.width / Screen.dpi) * 2.54f; screenWidth /= 100; } private void Update() { // float height = Camera.main.orthographicSize * 2.0f; // float width = height * Screen.height / Screen.width; // gameObject.transform.localScale = Vector3.one * width / SIZE_ON_SCREEN; float screenCenterX = (screenWidth / 2); float pointLeft = screenCenterX - (actualObjectSize.x / 2); float pointRight = screenCenterX + (actualObjectSize.x / 2); Debug.Log("Left " + pointLeft + " Right " + pointRight); float normalizedLeft = Normalize(pointLeft, 0, screenWidth); float normalizedRight = Normalize(pointRight, 0, screenWidth); Debug.Log("Left Normalized " + normalizedLeft + " Right Normalized " + normalizedRight); Vector3 expectedLeftEndPoint = Camera.main.ViewportToWorldPoint(new Vector3(normalizedLeft, 0.5f, Camera.main.transform.position.z)); Vector3 actualLeftEndPoint = transform.position - (Vector3.left * (transform.localScale.x / 2)); float newScale = (expectedLeftEndPoint.x * transform.localScale.x) / actualLeftEndPoint.x; transform.localScale = Vector3.one * newScale; } public void IncreaseSize() { // SIZE_ON_SCREEN += 0.1f; actualObjectSize += Vector2.one * 0.01f; sizeText.text = gameObject.transform.localScale.x.ToString() + " : " + actualObjectSize.x; } public void DecreaseSize() { // SIZE_ON_SCREEN -= 0.1f; actualObjectSize -= Vector2.one * 0.01f; sizeText.text = gameObject.transform.localScale.x.ToString() + " : " + actualObjectSize.x; } public float Remap(float unscaledNum, float minAllowed, float maxAllowed, float min, float max) { return (maxAllowed - minAllowed) * (unscaledNum - min) / (max - min) + minAllowed; } public float Normalize(float value, float minimum, float maximum) { return (value - minimum) / (maximum - minimum); } }