Boundaries Based on Sprite Dimensions in Lecture 5_LD_UY2

I wanted to share a solution that I managed to get working. Instead of adding serializable padding fields to to the sides of the screen you can use the InitBounds (or as I call it CalculateBounds) function to take into account the size of the player sprite and subtract or add it to the bounds of the screen.

This way if you ever change the playersprite or resize it the boundaries of the screen will adjust in script:

Felt like an absolute genius after figuring this out :smiley: :smiley: :smiley:

4 Likes

Hi! I know this is probably a long shot but do you still have the code?

I don’t know how you’re calling the player sprite (it is covered over in your image) and I wanted to implement this method myself

many thanks!

1 Like

Ah yes, the box is hiding that part of the code.

Just type

Sprite playerSprite = GetComponentInChildren().sprite;

1 Like

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;
    }
}

Privacy & Terms