你可以通過您的2點確定的線就和每個矩形從here複製
func intersectionBetweenSegments(p0: CGPoint, _ p1: CGPoint, _ p2: CGPoint, _ p3: CGPoint) -> CGPoint? {
var denominator = (p3.y - p2.y) * (p1.x - p0.x) - (p3.x - p2.x) * (p1.y - p0.y)
var ua = (p3.x - p2.x) * (p0.y - p2.y) - (p3.y - p2.y) * (p0.x - p2.x)
var ub = (p1.x - p0.x) * (p0.y - p2.y) - (p1.y - p0.y) * (p0.x - p2.x)
if (denominator < 0) {
ua = -ua; ub = -ub; denominator = -denominator
}
if ua >= 0.0 && ua <= denominator && ub >= 0.0 && ub <= denominator && denominator != 0 {
return CGPoint(x: p0.x + ua/denominator * (p1.x - p0.x), y: p0.y + ua/denominator * (p1.y - p0.y))
}
return nil
}
func intersectionBetweenRectAndSegment(rect: CGRect, _ p0: CGPoint, _ p1: CGPoint) {
var result = false
let topLeftCorner = rect.origin
let topRightCorner = CGPoint(x: rect.origin.x + rect.size.width, y: rect.origin.y)
let bottomLeftCorner = CGPoint(x: rect.origin.x, y: rect.origin.y + rect.size.height)
let bottomRightCorner = CGPoint(x: rect.origin.x + rect.size.width, y: rect.origin.y + rect.size.height)
if intersectionBetweenSegments(po, p1, topLeftCorner, topRightCorner) != nil {
return true
}
if intersectionBetweenSegments(po, p1, topRightCorner, bottomRightCorner) != nil {
return true
}
if intersectionBetweenSegments(po, p1, bottomRightCorner, bottomLeftCorner) != nil {
return true
}
if intersectionBetweenSegments(po, p1, bottomLeftCorner, topLeftCorner) != nil {
return true
}
return false
}
段交叉點代碼的4個邊之間線相交測試。
未經測試!
來源
2016-10-20 10:33:15
tsp
從2個點生成一個SKShapeNode,然後看看shapeNode和CGRect是否相交? –