0

I want to move a UIView inside of a circle. The UIView moves every point inside the circle but not touch border line of the circle. I am calculating distance between circle and the UIView.

var distance = sqrt(
    pow((touchPoint.x - selfCenter.x), 2) + pow((touchPoint.y - selfCenter.y), 2)
)

And limiting the UIView movement towards out of the circle

if distance <= radius {
    theUIView.center = touchPoint
}

The problem starts here, if touch move out from circle the UIView stuck at the border, inside the circle. That is why I am trying write else statement as far as I have tried this.

if distance <= radius {
    theUIView.center = touchPoint
} else {
    theUIView.center = CGPointMake(
      touchPoint.x / distance * radius,
      touchPoint.y / distance * radius
    )
}

Question is, how I can keep the UIView inside the circle and keep moving if touches keep moving. A hint would be great.

There are similar questions here -like this- but did not helped.

Community
  • 1
  • 1
modusCell
  • 13,151
  • 9
  • 53
  • 80

1 Answers1

2

Your else case looks wrong. If you want to "project" a point outside of the circle onto the circle boundary then it should be

if distance <= radius {
    theUIView.center = touchPoint
} else {
    theUIView.center = CGPointMake(
        selfCenter.x + (touchPoint.x - selfCenter.x) / distance * radius,
        selfCenter.y + (touchPoint.y - selfCenter.y) / distance * radius
    )
}

Remark: The distance can be more easily computed using the hypot() function:

var distance = hypot(touchPoint.x - selfCenter.x, touchPoint.y - selfCenter.y)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382