给出两点我如何确定矩形是否会通过连接点的线

时间:2016-10-20 10:08:20

标签: swift sprite-kit line

在我的代码中,我有两个点point1point2以及rectangle。一般来说,我想知道如何确定两个点的线是否会通过矩形。

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 个答案:

答案 0 :(得分:3)

您可以在由2个点确定的线与矩形的每个4边之间进行线交叉测试

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
}

here复制的段交叉代码。

未经测试!