I need to find the point (green dot) on the edges of any (not just squares) given rectangle (grey box) where a line(red line) starting from the centre of the rectangle would intersect the rectangle.
The function should look something like this:
func intersection(forAngle angle: CGFloat, rect: CGRect) -> CGPoint {
// Do magic here
}
gist for easy visualisation that you can paste into a macOS playground
This is what I have so far:
let t = tan(angle)
switch angle {
case 0..<(pi/2):
//top right corner - works but only for square rects
// t > 1 => top edge, t < 1 right edge
let x = t > 1 ? rect.width + (1 - t) * rect.width / 2 : rect.width
let y = t < 1 ? t * rect.height / 2 + rect.height / 2 : rect.height
return CGPoint(x: x, y: y)
case (pi/2)..<pi:
//top left corner
case pi..<(1.5*pi):
//bottom left corner
case 1.5*pi..<2*pi:
//bottom right corner
default:
return CGPoint.zero
}