获取 child SKSpriteNode 位置

Getting child SKSpriteNode Position

我目前正在尝试创建一个游戏,当平台离开场景时,它会在场景中自动生成平台。

我创建了 5 个 SKSpriteNode 并将它们作为 children 添加到平台 SKNode。

然后我在更新函数

中使用 platformGroupNode.position.x-- 将它们移过屏幕

但是,我想检测其中一个 children 何时离开屏幕,以便我可以生成一个新平台。

我试过下面的方法,但它似乎只给我一个 child 在 parent 节点

中的位置
for child in shipGroupNode.children {
            println(child.position.x)
        }

是否有更好的方法来对 Sprite 节点进行分组,以允许我查看它们与场景相关的各个属性并控制分组?

代码------------

mport SpriteKit

// Globals
let platformGroupNode = SKNode()
var platformX:CGFloat = 200

class GameScene: SKScene {
    override func didMoveToView(view: SKView) {

        platformGroupNode.position = CGPoint(x: 0, y: 0)
        addChild(platformGroupNode)

        // Add platforms
        addPlatform(platformX)

        // Add platforms
        for i in 1...4 {
            addPlatform(platformX)
            //println(platformX)
        }
    }

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        /* Called when a touch begins */
    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
        platformGroupNode.position.x--

        for child in platformGroupNode.children {
            println(child.position.x)
            println(convertPointToView(CGPoint(x: child.position.x, y: child.position.y)))
        }

    }

    func addPlatform(platformx:CGFloat) {
        let platform = SKSpriteNode(imageNamed:"Spaceship")

        platform.xScale = 0.5
        platform.yScale = 0.5
        platform.position = CGPoint(x: platformx, y: self.size.height/2)

        platformX = platformx + 200
        platformGroupNode.addChild(platform)
    }
}

可以在SKScene上使用intersectsNode方法检查child节点是否可见; intersectsNode 将 return true 而 children 可见。

for child in platformGroupNode.children {
    if let sprite = child as? SKSpriteNode where !intersectsNode(sprite) { 
        child.removeFromParent()

        // Generate new platform...
    }
}

除了删除然后创建新平台之外,另一种方法是重新定位刚刚移出屏幕的平台,这样它就会移回屏幕上。例如:如果从右向左滚动,当平台离开左边缘时,它将重新定位到右侧。这样的好处是一开始只需要创建几个平台。


要使其正常工作,您的 SKScenesize 必须等于其 SKView 大小。有关这方面的信息,请查看