- Home /
How to position objects UI elements in a line accounting for the rotation of the object
I have a set of UI objects that need to face the camera when I update their position. And when I add more objects to this set of UI Objects, I need to space them so that they are not touching, however due to their own rotation and position around my camera, I cannot simply add to the x value of the position or the z value of the position to gain the desired effect. I have the rotation part down, I just need help with positioning the objects in a line based on the Y rotation of the camera. So if the camera faces a 45 degree angle, the objects need to be positioned on the tangent line that would come from that angle on a circle.
Answer by ScaniX · Aug 17, 2016 at 09:05 PM
If you want to line up n items in front of the camera, you could set their position like this:
GameObject[] items = // this should be filled with your gameobjects
Vector3 camPos = Camera.main.transform.position;
Vector3 camForward = Camera.main.transform.forward;
Vector3 camRight = Camera.main.transform.right;
float distanceFromCamera = 5f;
float distanceFromEachOther = 2f;
int n = items.Length;
for (int i=0; i<n; i++)
items[i].transform.position = camPos + distanceFromCamera * camForward + (i - (n-1) / 2f) * distanceFromEachOther;
In plain text we move from the camera position forward (each transform has three easily accessible vectors: forward, right and up), then half of the total extents to the left (-right vector multiplied by (n-1)/2f) and then to the right one distance per element.
Your answer
Follow this Question
Related Questions
When creating joints during game play how do you change the position and rotation of an object. 0 Answers
Instantiate GameObject to specific position on the Parent 2 Answers
Moving an object in a circle towards joystick 0 Answers
Quaternion to rotate a GameObject and its children 1 Answer
Offset position to a target 3 Answers