I’m not sure if I do this correctly but I want to place my player always at the very bottom of the screen. Regardless of screen size, aspect or whatever. The problem is, I scale my player depending on the screen width which than leads to invalid values for the Y position. But how do I calculate the proper position?
This is what I currently use to scale my game objects:
public class Scaler : MonoBehaviour
{
void Awake()
{
var screenWidth = Camera.main.ScreenToWorldPoint(new Vector3(Screen.safeArea.width, Screen.height, 0)).x;
var spriteRenderer = GetComponent<SpriteRenderer>();
if (spriteRenderer == null)
spriteRenderer = GetComponentsInChildren<SpriteRenderer>().OrderByDescending(r => r.bounds.max.x).First();
if (gameObject.tag == "Player")
{
var playerSize = screenWidth / 5f;
var scaleFactor = playerSize / spriteRenderer.bounds.max.x;
transform.localScale = new Vector3(scaleFactor, scaleFactor, 1);
}
else
{
var playerSize = screenWidth / 20f;
var scaleFactor = playerSize / spriteRenderer.bounds.max.x;
transform.localScale = new Vector3(scaleFactor, scaleFactor, 1);
}
}
}
And this is my current state for the placement (which always leads to a way too low position for the player):
public class PlayerPlacement : MonoBehaviour
{
void Start()
{
var orthographicHeight = Camera.main.orthographicSize * Camera.main.aspect;
transform.position = new Vector3(transform.localPosition.x, -orthographicHeight, 0);
}
}
Is there something I miss? Or is there a better way for proper scaling and placements of gameobjects?