views:

79

answers:

3

I have a number of rectangular elements that I want to position in a 2D space. I calculate an ideal position for each element. Now my problem is that many elements overlap as very often the ideal positions are concentrated in one region. I want to avoid overlap as much as possible (doesn't have to be perfect, though). How can I do this?

I've heard physics simulations are suitable for this - is that correct? And can anyone provide an example/tutorial?

By the way: I'm using XNA, if you know any .NET library that does exactly this job - tell me!

+1  A: 

Box2D is a widly used (free) physics library that can achieve the needed task: Link

tur1ng
A: 

The algorithm that you are looking for is linear interpolation. XNA has its own lerp function.

Marcus Adams
That function is actually quite useful for me in another part of the project - but could you explain how exactly I can use it to solve the problem I mentioned?
eWolf
@eWolf, I've used the algorithm to properly distribute a bar graph over a specified pixel width. The algorithm allows you to properly size and space out objects so that the objects take up the whole space, without overlap.
Marcus Adams
+1  A: 

One way the physics engine can be used:

Put positive electric charges (or some kind of repulsive force) on each rectangles and simulate the forces and movements. Also, as Eyal was kind enough to point out, you also need some attractive forces to keep them from drifting away. This can be modelled by springs (again as Eyal points out). They will hopefully end up in some sort of equilibrium which might involve non-overlapping rectangles.

I believe similar ideas (force based heuristics) are used in determining nice looking layouts of graphs (the nodes and edges one).

Disclaimer: I haven't used this myself.

Hope that helps!

Moron
@Moron: I think that using only repulsive force will not end up in equilibrium. The force based algorithm for drawing graphs, for example, use both a repulsive force and an attractive force between the nodes (the first simulating electrical charges of the same sign, and the second simulating springs).
Eyal Schneider
@Eyal: Thanks, I will edit the answer. And my duh! Unless we contain the rectangles, repulsive forces will just cause them to drift away :-).
Moron
Thanks for your answer.. that sounds good. I just have to understand how I can do this with the Box2D library @tur1ng posted.
eWolf