<分区>
有没有一种简单的方法可以在 Swift 中绘制形状(最好使用 Sprite-Kit),然后检测它们是否相交以及相交的位置?就像这里的相交形状:
<分区>
有没有一种简单的方法可以在 Swift 中绘制形状(最好使用 Sprite-Kit),然后检测它们是否相交以及相交的位置?就像这里的相交形状:
最佳答案
如果这由一系列线段组成,则可以采用 Martin R 对 UIBezierPath intersect 的回答不仅要检测交叉点,还要识别交叉点的位置:
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
}
guard ua >= 0 && ua <= denominator && ub >= 0 && ub <= denominator && denominator != 0 else {
return nil
}
return CGPoint(x: p0.x + ua / denominator * (p1.x - p0.x), y: p0.y + ua / denominator * (p1.y - p0.y))
}
因此,如果您有一个 CGPoint
值数组并且您想要识别所有交叉点,您可以这样做:
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`
}
}
}
例如,您可以在屏幕的线段相交处添加一个点:
但是,如果您的曲线由三次贝塞尔曲线组成,则情况会更加复杂。不过,您可能会考虑 Checking if two cubic Bézier curves intersect .
关于ios - Swift:有没有一种简单的方法来绘制形状并检测它们是否相交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26943037/
相关文章:
objective-c - 我怎样才能使分数等于在 spritekit 中玩游戏的时间(以秒为单位)
swift - 更改 GameViewController 中变量的值 (SpriteKit Swift)
ios - UIActivityIndicator 随 tableView 滚动
iphone - appdelegate 方法中的 setBrightness?
ios - 设置 contentScaleType 时由于内存警告导致应用程序崩溃
ios - 获取 UITableView 错误 "unable to dequeue a cell with identifier cell"