Last active
September 27, 2016 23:46
-
-
Save densmoe/6f764c981249f09eb74f309f6e950f37 to your computer and use it in GitHub Desktop.
intersection point of rect and line problem (see: http://stackoverflow.com/questions/39735667/how-to-find-the-intersection-point-of-rect-and-a-line-starting-in-its-center)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
// Stackoverflow: http://stackoverflow.com/questions/39735667/how-to-find-the-intersection-point-of-rect-and-a-line-starting-in-its-center | |
import SpriteKit | |
import PlaygroundSupport | |
let pi = CGFloat(M_PI) | |
let angle = pi / 4 - 0.2 | |
let rect = CGRect(x: 0, y: 0, width: 150, height: 150) | |
func point(forAngle angle: CGFloat, rect: CGRect) -> CGPoint { | |
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) | |
default: | |
return CGPoint.zero | |
} | |
} | |
// Visualization Code | |
let view = SKView(frame: rect) | |
PlaygroundPage.current.liveView = view | |
let scene = SKScene(size: view.frame.size) | |
view.presentScene(scene) | |
let shape = SKShapeNode(rect: rect) | |
shape.fillColor = SKColor.clear | |
shape.strokeColor = SKColor.white | |
scene.addChild(shape) | |
let path = CGMutablePath() | |
path.move(to: CGPoint.zero) | |
path.addLine(to: CGPoint(x: rect.width, y: 0)) | |
let line = SKShapeNode(path: path) | |
line.position = CGPoint(x: rect.midX, y: rect.midY) | |
line.strokeColor = SKColor.red | |
scene.addChild(line) | |
line.run(SKAction.rotate(toAngle: angle, duration: 3)) | |
let dot = SKShapeNode(circleOfRadius: 4) | |
dot.strokeColor = SKColor.clear | |
dot.fillColor = SKColor.green | |
dot.position = point(forAngle: angle, rect: rect) | |
scene.addChild(dot) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment