SpriteKit:移动整个场景

时间:2015-11-10 19:09:06

标签: swift sprite-kit move scene

我想为场景添加特定数量的方块。当我这样做时,广场的一部分在视图之外。是否可以在y轴上移动整个场景?

1 个答案:

答案 0 :(得分:1)

我试过,看起来场景本身无法移动。另一种方法是将SKNode添加到代表整个世界的场景中。将所有其他元素添加到world节点。现在,如果要移动整个场景,可以移动此节点。我正在撰写关于我的博客的简短教程。这是我目前的代码:

import SpriteKit

class GameScene: SKScene {

// Declare the needed nodes
var worldNode: SKNode?
var spriteNode: SKSpriteNode?
var nodeWidth: CGFloat = 0.0

override func didMoveToView(view: SKView) {

    // Setup world
    worldNode = SKNode()
    self.addChild(worldNode!)

    // Setup sprite
    spriteNode = SKSpriteNode(imageNamed: "Spaceship")
    spriteNode?.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
    spriteNode?.xScale = 0.1
    spriteNode?.yScale = 0.1
    spriteNode?.zPosition = 10
    self.addChild(spriteNode!)

    // Setup backgrounds
    // Image of left and right node must be identical
    let leftNode = SKSpriteNode(imageNamed: "left")
    let middleNode = SKSpriteNode(imageNamed: "right")
    let rightNode = SKSpriteNode(imageNamed: "left")

    nodeWidth = leftNode.frame.size.width

    leftNode.anchorPoint = CGPoint(x: 0, y: 0)
    leftNode.position = CGPoint(x: 0, y: 0)
    middleNode.anchorPoint = CGPoint(x: 0, y: 0)
    middleNode.position = CGPoint(x: nodeWidth, y: 0)
    rightNode.anchorPoint = CGPoint(x: 0, y: 0)
    rightNode.position = CGPoint(x: nodeWidth * 2, y: 0)

    worldNode!.addChild(leftNode)
    worldNode!.addChild(rightNode)
    worldNode!.addChild(middleNode)


}


var xOrgPosition: CGFloat = 0
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for touch in touches {

        let xTouchPosition = touch.locationInNode(self).x
        if xOrgPosition != 0.0 {
            let xNewPosition = worldNode!.position.x + (xOrgPosition - xTouchPosition)

            if xNewPosition <= -(2 * nodeWidth) {
                // right end reached
                worldNode!.position = CGPoint(x: 0, y: 0)
                print("Right end reached")
            } else if xNewPosition >= 0 {
                // left end reached
                worldNode!.position = CGPoint(x: -(2 * nodeWidth), y: 0)
                print("Left end reached")
            } else {

                worldNode!.position = CGPoint(x: xNewPosition, y: 0)
            }
        }
        xOrgPosition = xTouchPosition
    }
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    // Reset value for the next swipe gesture
    xOrgPosition = 0
}

override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */
}

}