# Evenly distribution of 2 or more shapes given their x and y points inside a bounding box

I have a set of dynamically shaped objects, How do I distribute them evenly either Horizontally or Vertically.The objects are surrounded by a bounding box and the objects are placed at x,y as shown.

Can anyone help me in providing the algorithm or pseudo code. UPDATE: It is clear that, the shapes those stay at extremes (forming a bounded box) are kept constant and the remaining objects inside the space is distributed evenly. I used a word processing application to simulate the above example.

For 2 objects inside, • Are there aleays three in this same configuration? – Bálint Oct 19 '17 at 9:10
• Wait, do you need this for game developement? – Bálint Oct 19 '17 at 9:14

If you have a set of bounding boxes and the first and last one shouldn't get moved, then you can create a line out of the center points of these two and line the ither center points up with it.

So, the x position of the center of a bounding box given the line defined by A and B and the y position is

x = (B.x - A.x) * (y - A.y) /(B.y - A.y) + A.x


So if you need the upper left position, then subtract half of the width from the value you calculate with this formula

• @CodeGuy You can very quickly throw a prototype together with jsfiddle if you know javascript, but that's it – Bálint Oct 19 '17 at 11:10
• @CodeGuy can you post the code in a pastebin? – Bálint Oct 20 '17 at 7:48
• @CodeGuy You need to set the center's x to the new x, if you have to set the left edge, then subtract width / 2 from it – Bálint Oct 20 '17 at 17:32
• @CodeGuy My answer clearly states, that it gives you the center, so I'll only change it a bit – Bálint Oct 21 '17 at 16:02