0

I have a dynamic list of objects and need to place them around a centre object without overlapping. They are all rectangle shapes. I am using Java FX text objects.

If I place the first object in the centre with

int x =(int)(scene.getWidth() /2);
int y =(int)(scene.getHeight() /2);

How do I position the others around it without overlapping.There are n amount of objects.

I am not sure how to detect the collision and then move them once the collision has been detected.

if collision = true {
                translate x 30 px{
                if still true {
                translate y 30{
                if still true{
                translate x -30
                if still true{
                translate y -30{
                if still true {
                start again but increase movement size by 20 each iteration 
                until collision free placement occurs.


                x----->----x
                |          |
                ^          |
                |          |
                |          |
                x----<-----x

Thanks

1 Answers1

0

To determine whether two rectangles overlap you can create instances of them as java.awt.Rectangle and then call the intersects method to see whether they overlap. You can also use the intersection method to calculate by how much you have to move one to not have an intersection with the other.

You also had the question how you would move them. My first idea is that you should do it like a LayoutManager. Extend Parent and override the layoutChildren() method and lay them out there as you want them. It allows you to set absolute coordinates for the rectangles, after you calculated an arrangement that is collision free.

This algorithm would be rather computational expensive if you have to always check for intersections with all n other rectangles. Maybe you want to look at a LayoutManager like FlowPane to optimize that. FlowPane will layout the objects in a line until the boundary and then break to the next line. (or columns if it is vertically)

There are other ways to optimize it if you cannot use a LayoutManager, but I need more information about the use case to help you with that. Depending on the use-case maybe this question can help you.

findusl
  • 2,454
  • 8
  • 32
  • 51