无法移动我的skspritenodes编辑:

时间:2016-01-01 15:43:51

标签: swift sprite-kit skspritenode

func increaseSnakeLength(){

    snakeArray.append(snakeLength)
    inc += snakeBody.size.height

    if snakeMovingLeft == true{
        snakeLength = SKSpriteNode(texture: nil, color: UIColor.blueColor(), size: CGSizeMake(20, 20))
        snakeLength.position = CGPointMake(snakeBody.position.x + inc, snakeBody.position.y )
        addChild(snakeLength)
    }
    if snakeMovingRight == true{
        snakeLength = SKSpriteNode(texture: nil, color: UIColor.blueColor(), size: CGSizeMake(20, 20))
        snakeLength.position = CGPointMake(snakeBody.position.x - inc, snakeBody.position.y)
        addChild(snakeLength)
    }
    if snakeMovingUp == true{
        snakeLength = SKSpriteNode(texture: nil, color: UIColor.blueColor(), size: CGSizeMake(20, 20))
        snakeLength.position = CGPointMake(snakeBody.position.x, snakeBody.position.y - inc)
        addChild(snakeLength)
    }
    if snakeMovingDown == true{
        snakeLength = SKSpriteNode(texture: nil, color: UIColor.blueColor(), size: CGSizeMake(20, 20))
        snakeLength.position = CGPointMake(snakeBody.position.x, snakeBody.position.y + inc)
        addChild(snakeLength)
    }
}
func moveSnake(){

    if snakeArray.count > 0{
        snakeLength.position = CGPointMake(snakeBody.position.x, snakeBody.position.y)
    }
    snakeBody.position = CGPointMake(snakeHead.position.x, snakeHead.position.y)
    snakeHead.position = CGPointMake(snakeHead.position.x + snakeX, snakeHead.position.y + snakeY)
}

[蛇游戏] [1] [1]:http://i.stack.imgur.com/nhxSO.png

我的函数increaseSnakeLength()在snakeHead与我的食物接触时为场景添加了一个新的snakeLength块。然后在我的moveSnake()函数中移动蛇块,但是当我移动snakeLength块时,它只移动最新的块并使旧块不移动。您可以在上图中看到这一点。我不知道如何同时移动所有的snakeLength区块。

2 个答案:

答案 0 :(得分:0)

看起来snakeLength是一个全局变量。这意味着每次你吃这些食物,你都会覆盖你的食物。在moveSnake()中,检查snakeArray的大小,但从不访问数组本身。我建议通过所有索引的for循环,更新它们的位置。

我还建议将snakeArray.append(snakeLength)放在increaseSnakeLength()的底部,让它添加最新的蛇形部分。

答案 1 :(得分:0)

您正在做的是使用SKNode作为父节点的完美示例。 SKNode用作精灵的抽象容器,允许您集体移动/缩放/动画分组的精灵/节点。

不要将精灵添加到场景本身,而是尝试这样的事情:

为你的蛇创建一个SKNode课程(让你控制蛇并将关注点分开一点):

class Snake : SKNode {

    func grow(){
        let snakeLength = SKSpriteNode(texture: nil, color: UIColor.blueColor(), size: CGSizeMake(20, 20))
        // NOTE! position will now be relative to this node
        // take this into account for your positioning
        snakeLength.position = CGPointMake(snakeBody.position.x - inc,         snakeBody.position.y)
        self.addChild(snakeLength)
    }  

    func moveLeft() { // moves the snake parts to the left (do this for all your directions)
        // iterate over all your snake parts and move them accordingly
        for snakePart in self.children {

        }
    }      

}

在你的主场景中,你可以创建蛇:

let snake = Snake()

// when the snake eats food, grow the snake
snake.grow()

通过对蛇本身执行动作来移动蛇及其部分:

// In your main scene
snake.moveLeft()