George Bland
George Bland

Reputation: 39

I want to centre the unity camera to the top right corner

I created this code to move the camera half its width right and half its height up to make the top right the new centre, it did not work, where did I go wrong?

Camera.main.transform.position=Camera.main.ViewportToWorldPoint(new Vector2((float)0.5,(float)0.5));

This is 2d mode by the way.

Upvotes: 0

Views: 1333

Answers (2)

derHugo
derHugo

Reputation: 90600

Well 0.5, 0.5 is literally the center of the Viewport!

0,0 is the bottom left corner and 1, 1 the top right.

You probably would rather do e.g.

Camera.main.transform.position = Camera.main.ViewportToWorldPoint(Vector2.one);

Btw just s general hint: Instead of (float)0.5 you would rather directly use 0.5f ;)

Upvotes: 1

TimS
TimS

Reputation: 69

I think what you want is to change the viewport rect. In Unity editor, in the inspector, select your camera, and change viewport rect to x: 0.5, y: 0.5, w: 0.5, h: 0.5. Changing the position only changes the world-space position of the camera (e.g. moving it to the right when mario moves to the right).

edit: Okay so to do it in code

Camera.main.rect = new Rect(0.5f, 0.5f, 0.5f, 0.5f);

edit:edit: To explain further, you set x and y to 0.5 to move it half the screen width and and half the screen height. Then you set width and height to 0.5 to also make them half the screen width and height. If you intended to have the camera centered on the top right but for some reason extend off the screen as well, you would leave width and height at 1.

Upvotes: 0

Related Questions