ios - swift - SpriteKit : Make sprites reacting to eachothers if added with different "addchild" parents

标签 ios swift sprite

我在我的场景中添加了几个 Sprite (SKSpriteNode),如下所示:

let NPuzzle_Texture = SKTexture(imageNamed: "SKTexture.png")
NPuzzle0 = SKSpriteNode(texture: NPuzzle_Texture)
NPuzzle1 = SKSpriteNode(texture: NPuzzle_Texture)
NPuzzle2 = SKSpriteNode(texture: NPuzzle_Texture)
NPuzzle0.position = CGPoint (x: 100, y:125)
NPuzzle0.position = CGPoint (x: 300, y:125)
NPuzzle0.position = CGPoint (x: 500, y:125)
background.addChild(NPuzzle0)
background.addChild(NPuzzle1)
background.addChild(NPuzzle2)

我还添加了几个不同纹理的 Sprite :

let Grey_Back = SKTexture(imageNamed: "Grey_Back.png")
grey_back = SKSpriteNode(texture: Grey_back)
grey_back.position = CGPoint (x: 1024, y:125)
grey_back.alpha = 0.5
background.addChild(grey_back)

现在我像这样向先例 grey_back 添加新的 Sprite (SKSpriteNode):

grey_back.addChild(new_sprite1)
grey_back.addChild(new_sprite2)
grey_back.addChild(new_sprite3)

当我尝试查看 new_sprite 的位置是否与 NPuzzle Sprite 相交时,没有任何反应。但是如果将 new_sprite 添加到场景中:

background.addChild(new_sprite0)
background.addChild(new_sprite1)
background.addChild(new_sprite2)

它有效。事实上,如果 Sprite 已经添加了不同的 parent (背景和 grey_back),它就不起作用。我不明白的是 grey_back 是背景的 child ,所以,它应该工作。为什么不呢?

这是检查 Sprite 是否相互交叉的代码示例:

switch selectedNode.name {

case "new_sprite0":
if selectedNode.frame.intersects(NPuzzle0.frame) && (selectedNode.angle == 0) {

谢谢!

最佳答案

switch selectedNode.name {
let framePoint = CGPointMake(selectedNode.frame.origin.x, selectedNode.frame.origin.y)
let translatedPoint = selectedNode.parent!.convertPoint(framePoint, toNode:NPuzzle0.parent!)
let translatedFrame = CGRectMake(translatedPoint.x, translatedPoint.y, selectedNode.frame.size.width, selectedNode.frame.size.height)
if translatedFrame.intersects(NPuzzle0.frame) && (selectedNode.zRotation == 0) 
{
    print("ok")
}

显然,因为帧是相对于父节点的,所以必须将节点添加到场景中。你可以看到我还为父级使用了强制解包...

关于ios - swift - SpriteKit : Make sprites reacting to eachothers if added with different "addchild" parents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37814726/

相关文章:

objective-c - NSString 让我大吃一惊

ios - 如何解决 Xcode 10 beta 中的错误 "linker command failed with exit code 1 (use -v to see invocation) "?

ios -> -[UITableView dequeueReusableCellWithIdentifier :forIndexPath:] 断言失败

swift - 从 objective-c 转换到 swift

python - Pygame Sprite 表 hitbox 损坏

ios Swift - 使用同步动画对分离的 Sprite 进行分组

ios - Urban Airship 在调用起飞时坠毁

ios - 存折."The card has expired"

ios - UICollectionView 的动态单元格宽度取决于标签宽度

opengl - 在单个纹理中存储多个纹理