2016-01-01 42 views
-1
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有麻烦移动我的skspritenodes编辑:

我的功能increaseSnakeLength()增加了一个新的snakeLength块到现场的时候,黑鱼,使我接触食品。然后在我的moveSnake()函数中移动蛇块,但是当我移动snakeLength块时,它只会移动最新的块并使旧块不移动。你可以在上面的图片中看到这个。我不知道如何同时移动所有的snakeLength块。

+0

蛇只能向上/向下/向左/向右移动,还是可以以任何角度移动? – 0x141E

+0

蛇只根据滑动的方向左右移动/上/下移动 – user3856516

回答

0

看来snakeLength是一个全局变量。这意味着每次你吃的食物,你都覆盖你的参考。在您的moveSnake()中,您检查snakeArray的大小,但不要访问阵列本身。我建议使用for循环遍历所有索引,更新它们的位置。

我也建议把snakeArray.append(snakeLength)放在increaseSnakeLength()的底部,让它得到最新的蛇部分。

0

你在做什么是一个使用SKNode作为父节点的完美例子。 SKNode s可作为您的精灵的抽象容器,允许您共同移动/缩放/动画分组的精灵/节点。

而不是增加你的精灵在场景本身,尝试这样的事情:

为你的蛇创建一个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() 

而且移动蛇,它通过对零食执行动作的部件e本身:

// In your main scene 
snake.moveLeft()