Home > Blockchain >  How to constrain a moving circle in a larger circle
How to constrain a moving circle in a larger circle

Time:09-27

I am working on a problem in iOS that involves a moving circle (circle a of radius r) within a larger static circle (circle b of radius t). t > r.

Circle a can move anywhere within circle b, but stops as soon as it touches circle b. I'm implementing the rendering of the circle by adding x and y offsets to the starting center point of circle a, and redrawing it each time. The calculations for the offsets are being made using some gravity and friction coefficient values. I understand that I have to subtract some value from the offsets if circle a goes out of circle b. How do I calculate the offsets in a way that circle a is constrained within circle b?

I can achieve the same when constrained in a rectangle, but scratching my head making the calculations for constraining it in a circle.

Any help is greatly appreciated.

CodePudding user response:

This is a lot easier if you change where the calculation is. Instead of trying to calculate whether the circumference of the inner circle goes outside the outer circle you can reduce this to look at the centres.

If you have an outer circle of radius R and an inner circle of radius R' then, because they are circles we can say that if the inner circle centre is greater than (R - R') away from the centre it will be outside the outer circle.

So, if the centre of the outer circle is at (0,0) then we just need to calculate the Pythagorean distance of the centre of the inner circle.

If the coordinates of the centre of the inner circle is (x,y) then we can do the calculation…

if x*x   y*y > (R - R') * (R - R') {
  // inner circle is outside outer circle
}

If the outer circle centre is not at (0,0) then you just have to use dx and dy in the calculation where dx = outer circle centre x - inner circle centre x and same for dy.

  • Related