Thank for this, I implemented your solution to my project, I also added the option to adjust bounds if needed.
[Header(“GameField Settings”)]
[Range(0, 5)][SerializeField] int paddingTop;
[Range(0, 5)][SerializeField] int paddingBottom;
void Start()
{
initBounds();
rb = GetComponent<Rigidbody2D>();
}
private void initBounds()
{
Camera mainCamera = Camera.main;
minGameFieldBounds = mainCamera.ViewportToWorldPoint(new Vector2(0, 0));
maxGameFieldBounds = mainCamera.ViewportToWorldPoint(new Vector2(1, 1));
//Adjust screenbounds based on player sprite
SpriteRenderer playerSprite = GetComponentInChildren<SpriteRenderer>();
Vector2 spriteBounds = new Vector2(playerSprite.bounds.extents.x, playerSprite.bounds.extents.y);
//Traps the sprite of the player inside the playable area
minGameFieldBounds.x += spriteBounds.x;
minGameFieldBounds.y += spriteBounds.y;
maxGameFieldBounds.x -= spriteBounds.x;
maxGameFieldBounds.y -= spriteBounds.y;
//Player adjusted padding
if (paddingTop > 0 || paddingBottom > 0)
{
minGameFieldBounds.y += paddingBottom;
maxGameFieldBounds.y -= paddingTop;
}
}