Is there a way to avoid collisions? E.g. 20 circles that don’t overlap

I am just starting out with processing.

I wondered if there was a way to prevent ‘collisions‘?

For example, I would like to have 20 circles on a canvas and ensure that none of them overlap or touch each other.

Is this possible with simplistic code?

Thanks.

1 Like

Hi

welcome to our community

This is a good start

1 Like

Hi @GoodJuJu,

I would say that the solution would depends mainly on your use case and the performance you are aiming for.

The more simplistic approach I could think of is the following in pseudo code:

declare an array to hold the circles to draw on canvas

While the number of circle in the array is less than 20:
    chose a random (x, y) coordinates where you will draw your next circle
    
    for all circles in the array:
        Check if the distance between its center and the center of the new circle is larger than the sum of their radius
        if it is not the case:
            move to the next loop

    Add the new circle to the array. Since you arrive at this line, it means that you did not move to the next loop which means that the distance between the new circle and each of the other circles is larger than the sum of their radius which means that it is not overlapping either of them.
1 Like

Hi jb4x,

Thanks for your suggestion, it’s a good idea, I like it.

Thank you also for taking the time to provide a working example.

Thanks Jafal,

That was what I was looking for. I am trying to find my way around.

Appreciate you taking the time to provide the link

1 Like

This sounds like an assignment

But in any case

Haha it does, yet you solved it for him anyway…

2 Likes

I mean any teacher worth their salt will ask them to explain the logic or why they chose to complete the project the way they did, and in that case the teacher would find out the student doesnt know how he achieved the result.

If they can figure out the code and the logic and explain it, then its fine though. Plus this is coded in p5.js, the question was in processing java, so they still have to complete the conversion.

Assignment?? No… I’m 48…

I was waiting for my son to come out of school and the question popped into my head…. I thought I would ask and was very pleasantly surprised with the responses. Seems like a nice, helpful community… hopefully I can pay the kindness back myself one day.

1 Like

Well thanks for sharing. Its just circle packing as its called is often an introductory problem in coding

1 Like

Wow! Who knew? Hopefully great minds think alike… :slight_smile:

1 Like

@GoodJuJu
Hi

Watch this link very useful

https://funprogramming.org/