- Home /
Positioning Objects in a 2D Project
I am making a 2D pong game. The only thing that is eluding is initially placing the paddles on the screen. My intention is to place them just a little bit away from the right and left bounds of the camera. When I initially start my game, they are in a funky position.
I have a game over screen with a replay option. When I lose and do the replay, the paddles are exactly where I want them.
Here is my code for figuring out the positions of each paddle.
Right paddle (in the Start function):
bottomLeft = Camera.main.ScreenToWorldPoint(new Vector2(0, 0));
topRight = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height));
Debug.Log("TopRightX: " + GameManager.topRight.x.ToString());
Debug.Log("TopRighty: " + GameManager.topRight.y.ToString());
Vector 2 pos = Vector2.zero;
pos = new Vector2(topRight.x, 0);
pos -= Vector2.right * transform.localScale.x;
transform.position = pos;
Debug.Log("rPaddlePosition: " + transform.position.ToString());
Left paddle (in the Start function):
Debug.Log("BotttomLeftX: " + bottomLeft.x.ToString());
Debug.Log("BotttomLeftY: " + bottomLeft.y.ToString());
pos = new Vector2(bottomLeft.x, 0);
pos += Vector2.right * transform.localScale.x;
transform.position = pos;
Debug.Log("lPaddlePosition: " + transform.position.ToString());
These are the outputs on the first time loading.
TopRightX: 0
TopRighty: 0
rPaddlePosition: (-0.3, 0.0, 0.0)
BotttomLeftX: -10.46591
BotttomLeftY: -5
lPaddlePosition: (-10.1, 0.0, 0.0)
These are the outputs after I go through the game over screen and replay the game.
TopRightX: 10.46591
TopRighty: 5
rPaddlePosition: (10.1, 0.0, 0.0)
BotttomLeftX: -10.46591
BotttomLeftY: -5
lPaddlePosition: (-10.1, 0.0, 0.0)
My replay functionality is just a
SceneManager.LoadScene(0);
Where the scene index of the "game play scene" is 0. I'd appreciate any insight into getting the paddles placed correctly the first time.
Judging by the outputs, it looks like the view was square when the values were calculated. Do you have "$$anonymous$$aximise on Play" checked off in the game window? The values could match the dimensions of the game view in edit mode. Can you add a screenshot of your editor layout?
Answer by James_BadAlchemy · Feb 08, 2019 at 03:10 AM
I ran into a lot of the same issues as you doing it that way. It's better, if you haven't already, to use the Canvas system unity offers. It has built-in functionality for stretching, filling, padding, ratios, etc. You just gotta play around with it.
Answer by solarsaenz · Mar 07, 2019 at 12:47 AM
For some reason, when I updated my Unity, this just "automagically" started working for me. Not sure if i ran into a Unity bug, or if Unity just was optimized in some way to account for whatever I was doing. Thank you to those who offered a response.