- Home /
Help positioning an object on a 2D plane
I have a prefab on top of which I'm trying to position another game object but I can't figure out the positioning. It's really confusing to me. Here is the code I thought should work (comments show the actual run time values I'm working with).
Vector3 screenPos = Camera.main.WorldToScreenPoint(transform.position); // value (496.0, 558.0, 5)
Vector3 offset = new Vector3((renderer.bounds.size.x * 100) / 2, 0); // value (575.5, 0, 0)
Vector3 newPosition = screenPos - offset; // value (-79.5f, 558.0, 5.0)
When I draw an object at position screenPos I get something in the very center of my prefab so I know that "screenPos" is a position in the center of my prefab.
From there, though things are a bit merky. From my understanding of the Unity coordinate system the value in screenPos should be the ScreenPoint representation of the absolute position of the center of my game object in relation to the entire window. The offset value should be half the horizontal size of the game object in the same unit system as my screenPos and the newPosition variable should be an absolute position on the very far left of my game object in relation to the entire window. However ... something no es bueno because it is just not working. As you can see from the 3rd line above the x value is negative so won't be displayed on screen.
Here is a shot showing where my prefab is in the window for reference. The red box shows the position I'm trying to calculate with my code.
Answer by omatase · Sep 02, 2014 at 03:35 AM
Well gosh darnit 5 days of trying to understand this and after banging on it myself for that long I finally figured it out. The problem I'm having with this specific code is it doesn't account for scaling. I just assumed that if I did nothing it would keep my image assets sized at their default size. Of course that's not the case, I just hadn't thought it through until now.
Also, honestly this is the first time I've ever used an orthographic camera and so I had to learn the hard way how to use it. Now, knowing how to use it the problem is so simple to solve.
Here's the fixed code:
Vector3 screenPos = transform.position - new Vector3((renderer.bounds.size.x / 2), 0, 0);