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]: https://i.stack.imgur.com/nhxSO.png
我的函数 increaseSnakeLength(( 在蛇头与我的食物接触时向场景中添加了一个新的 snakeLength 块。然后在我的 moveSnake(( 函数中,我移动了蛇块,但是当我移动 snakeLength 块时,它只移动最新的块,而让旧块不移动。您可以在上图中看到这一点。我不确定如何同时移动所有蛇长度块。
看起来snakeLength
是一个全局变量。这意味着每次你吃食物时,你都在覆盖你对它的引用。 在你的moveSnake()
中,你检查snakeArray
的大小,但从不访问数组本身。 我建议for
循环遍历所有索引,更新它们的位置。
我还建议将snakeArray.append(snakeLength)
放在increaseSnakeLength()
的底部,以使其添加最新的蛇部分。
您正在做的是使用 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()