【发布时间】:2015-06-12 21:22:52
【问题描述】:
我在 iOS8.3 上使用 iOS SpriteKit Game Swift 模板。我正在尝试使用函数func intersectsNode(_ node: SKNode) -> Bool 来检测创建为 SKShapeNodes 的两个圆圈的重叠。事实证明,如果它的 SKShapeNodes 函数没有检测到交叉点。但是在进一步的故障排除中,如果我使用模板的默认 Spaceship sprite,则该功能可以正常工作。这是有效的代码:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
let sprite = SKSpriteNode(imageNamed:"Spaceship")
sprite.xScale = 0.3
sprite.yScale = 0.3
sprite.position = location
self.circles.append(sprite)
self.addChild(sprite)
if circles.count == 1 {
println("One circle")
} else {
for var index = 0; index < circles.count-1; ++index {
if sprite.intersectsNode(circles[index]) {
println(circles[index].frame)
println("Circle intersects another")
}
}
}
}
}
当上述代码中两个精灵重叠时,该函数返回 YES 并打印交集字符串。这是不起作用的代码:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
let sprite = SKShapeNode(circleOfRadius: 50)
sprite.position = location
self.circles.append(sprite)
self.addChild(sprite)
if circles.count == 1 {
println("One circle")
} else {
for var index = 0; index < circles.count-1; ++index {
if sprite.intersectsNode(circles[index]) {
println(circles[index].frame)
println("Circle intersects another")
}
}
}
}
}
如您所见,代码块完全相同,除了一种情况是 SKSpriteNode,另一种情况是 SKShapeNode。我还打印了 SKShapeNode Circles 的框架,我可以看到它们有有效的框架。所以我对此感到困惑,因为我现在想在我的代码中使用 SKShapeNodes 但我不能使用 intersectNode 函数,因为它不起作用。
【问题讨论】:
-
检查节点的边界框。帧大小和位置。顺便说一句,如果您认为 intersectNode 是一个智能函数,那么它确实不是。它只是检查两个帧是否共享任何点。如果一个节点与一个圆的边界框的角相交,它将被认为是相交的。
-
我对边界框的触摸和返回“是”的函数很好。但对我来说什么都没有发生。我已经用 Circles 和 Rects 试过了。看起来 intersectNode 只是不认为 SKShapeNodes 值得回覆,而只喜欢 SKSpriteNodes。除非我做错了什么。您可以在默认的 iOS Swift 游戏模板中尝试我的代码。您只需将
touchesBegan方法替换为我上面的方法即可。 -
您是否尝试过将 skshapenode 包含为 skspritenode?尝试将 skshapenode 添加为子节点。如果您需要访问它并且不想将其声明为变量,那么有一个有用的 name 属性
标签: ios swift sprite-kit skspritenode skshapenode