cuenta microsoft
cuenta microsoft

Reputation: 1

how do i strech game objects depending on resolution in unity2D 2021.3.15f1

so i have a game where i need gameobjects to bounce off the edge of the screen and detect when that bounce happens, right now i have some gray rectangles just outside of the camera and i detect when the circles bounce of of them but i have it set up so it has a fixed aspect ratio (16:9) and i'd like for it to be played in any screen size, how can i do that?

i asked chatgpt about it and it gave me a lot of answers but none worked, i serched it here but i didnt find it and i saw some youtube tutorials but none worked either

Upvotes: -1

Views: 28

Answers (1)

Voidsay
Voidsay

Reputation: 1550

Put the following script on an empty gameobject

using UnityEngine;

[RequireComponent(typeof(EdgeCollider2D))]
public class Screenbounds : MonoBehaviour
{
    private EdgeCollider2D col;
    private Camera mainCam;

    void Start()
    {
        col = GetComponent<EdgeCollider2D>();
        mainCam = Camera.main;
        UpdateScreenEdge();
    }

    public void UpdateScreenEdge()
    {
        Vector2[] screenEdgePoints = new Vector2[5];
        screenEdgePoints[0] = mainCam.ScreenToWorldPoint(new Vector3(0, 0));
        screenEdgePoints[1] = mainCam.ScreenToWorldPoint(new Vector3(0, Screen.height));
        screenEdgePoints[2] = mainCam.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height));
        screenEdgePoints[3] = mainCam.ScreenToWorldPoint(new Vector3(Screen.width, 0));
        screenEdgePoints[4] = screenEdgePoints[0];
        col.points = screenEdgePoints;
    }
}

This script will automatically add an edge collider component and set it up at runtime so that it covers the edges of the screen. If you resize the screen resolution you should call the UpdateScreenEdge function to update the edge points. Don't go too wild resizing, since your bouncing objects can easily glitch out of bounds.

Upvotes: 0

Related Questions