0
\$\begingroup\$

I have a grid based game. The main map is 2d array with land ids, something like this (here are 2 lands on the map, one formed where the 1's are and one formed by where the 2's are):

[ 1 , 2 , 2 ]
[ 1 , 1 , 2 ]
[ 1 , 2 , 2 ]

I want to draw buildings on the center of each land. But how is better to calculate the center? Just calculating mean(X),mean(Y) does not work - lands can bee narrow or have dumbbell shape.

\$\endgroup\$
  • \$\begingroup\$ Calculating the physical center of mass could be a viable approach. But I am not sure how one would do this for a tilemap. Keep in mind that even this point is not necessary on land (take a ring-shaped island, for example). Maybe try to find the point which is furthest away from a water tile? \$\endgroup\$ – Philipp Jun 5 '15 at 13:38
1
\$\begingroup\$

I'm aware it is not exactly what you're looking for, but here is a suggestion.

You could control the generation of your lands to force them to be convex.

Using this method would allow you to simply use the mean x and mean y values to place your building as you would be sure they're on the land.

Otherwise, the only options I see is 1) no random in the building placement, you place them manually, or 2) go with a more complex algorithm in determining the 'center' of the land: calculate the spot where there is, on average, the most land between the tested spot and the neighbour land or the side of the map.

\$\endgroup\$
0
\$\begingroup\$

Instead of getting the center of each land with mean(X) and mean(Y) (which, by the way, is not a bad solution), you could calculate a rectangular bounding box around each of your lands:

Land 1: Starting at (0, 0) of size (2, 3)
Land 2: Starting at (1, 0) of size (2, 3)

This way, you could calculate the relative center of the given rectangles:

Land 1: (2 / 2 + 0, 3 / 2 + 0) = (1, 1.5)
Land 2: (2 / 2 + 1, 3 / 2 + 0) = (2, 1.5)

If you want your buildings to be aligned with the grid, you can ceil the values

Land 1: ceil(1, 1.5) = (1, 2)
Land 2: ceil(2, 1.5) = (2, 2)

This will give you a good approximate of the center of each of your lands. THe approximation will not be very accurate for small grids (as you can see) but with bigger sizes it should give better results.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.