斯威夫特:有没有一种简单的方法来绘制形状并检测它们是否相交? [英] Swift: Is there an easy way to draw shapes and detect whether they intersect?

查看:130
本文介绍了斯威夫特:有没有一种简单的方法来绘制形状并检测它们是否相交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以在Swift中绘制形状(最好使用Sprite-Kit),然后检测它们是否以及在何处相交?就像这里是一个相交的形状:



解决方案

如果这包含一系列线段,可以将Martin R的答案改为。


Is there an easy way to draw shapes in Swift (preferrably with Sprite-Kit) and then detect if and where they intersect? Like here's an intersecting shape:

解决方案

If this consists of a series of line segments, one can adapt Martin R's answer to UIBezierPath intersect to not only detect intersections, but to also identify where the intersections are:

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
}

Thus, if you have an array of CGPoint values and you want to identify all of the intersections, you could do something like:

let n = points!.count - 1

for i in 1 ..< n {
    for j in 0 ..< i-1 {
        if let intersection = intersectionBetweenSegments(points![i], points![i+1], points![j], points![j+1]) {
            // do whatever you want with `intersection`
        }
    }
}

For example, you can add a dot to the screen where the segments intersect:

If, however, your curve consists of cubic bezier curves, it's more complicated. You might consider, though, Checking if two cubic Bézier curves intersect.

这篇关于斯威夫特:有没有一种简单的方法来绘制形状并检测它们是否相交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆