2016-10-20 11 views
1

在我的代碼下面我有兩點point1point2rectangle。一般來說,我想知道如何確定兩點的直線是否會穿過矩形。給出兩點我如何確定矩形是否會通過加入點的線

var point1 = CGPoint(x: screenSize.width/4,y: screenSize.height/4) 
var point2 = CGPoint(x: 3*screenSize.width/4,y: 3*screenSize.height/4) 
var rectangle = CGRect(x: sprite.position.x, y: sprite.position.x/2, width: sprite.frame.width, height: sprite.frame.height)) 
+1

從2個點生成一個SKShapeNode,然後看看shapeNode和CGRect是否相交? –

回答

3

你可以通過您的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個邊之間線相交測試。

未經測試!

相關問題