pixelgaming579
pixelgaming579

Reputation: 31

Creating a box collider 2D for the camera view

I was wondering why this isn't working. It is an Orthographic camera.

    Camera cam;
    BoxCollider2D camCollider;
    float halfHeight, halfWidth;
    void Start()
    {
        cam = this.gameObject.GetComponent<Camera>();
        camCollider = this.gameObject.GetComponent<BoxCollider2D>();
        halfHeight = Camera.main.orthographicSize;
        halfWidth = Camera.main.orthographicSize * (Screen.height / Screen.width);

        camCollider.size = new Vector2(halfHeight * 2, halfWidth * 2);
    }

halfHeight always end up as 11 and halfWidth ends up as 0 no matter what size I change the Game window to. I don't no why it produces those numbers.

Upvotes: 0

Views: 408

Answers (1)

Daniel M
Daniel M

Reputation: 766

Unfortunately your math is wrong. This should work:

float height = cam.orthographicSize * 2;
float width = height * cam.aspect;

camCollider.size = new Vector2(width, height);

Upvotes: 1

Related Questions