如何使用SKAction更改SKSpriteNode的位置

时间:2017-09-11 16:16:28

标签: swift sprite-kit skaction

while word != ""{

    if word[word.startIndex] == "R" {

        let moveSpriteToRight = SKAction.move(to: CGPoint(x: sprite.position.x+128, y: sprite.position.y), duration: 1)

        sprite.run(moveSpriteToRight)

    } else if word == "D" {

        let moveSpriteToDown = SKAction.move(to: CGPoint(x: sprite.position.x, y: sprite.position.y-128), duration: 1)

        sprite.run(moveSpriteToDown)

    } else if word == "L" {

        let moveSpriteToLeft = SKAction.move(to: CGPoint(x: sprite.position.x-128, y: sprite.position.y), duration: 1)

        sprite.run(moveSpriteToLeft)

    } else if word == "U" {

        let moveSpriteToUp = SKAction.move(to: CGPoint(x: sprite.position.x, y: sprite.position.y+128), duration: 1)

        sprite.run(moveSpriteToUp) 
    }

    word.remove(at: word.startIndex)
}

这是我的代码的一部分。我不能多次使用SKAction。例如,如果单词=“ULD”,那么精灵应该沿着路径向上移动(U),然后向左(L)向下移动(D)。每次通过手势,用户创建新的轨迹,记录手势的终止通过touchesEnded发生。精灵他们必须每次都执行。但是我的模拟器中的精灵在这个例子中将位置改为Down。

1 个答案:

答案 0 :(得分:0)

您可以将操作放入数组中,并在完成所有检查后将其作为序列运行

let actions = [SKAction]()

while word != ""{

    if word[word.startIndex] == "R" {
        actions.append(SKAction.move(to: CGPoint(x: sprite.position.x+128, y: sprite.position.y), duration: 1))
    }

    if word == "D" {
        actions.append(SKAction.move(to: CGPoint(x: sprite.position.x, y: sprite.position.y-128), duration: 1))
    } 

    if word == "L" {
        actions.append(SKAction.move(to: CGPoint(x: sprite.position.x-128, y: sprite.position.y), duration: 1))
    } 

    if word == "U" {
        actions.append(SKAction.move(to: CGPoint(x: sprite.position.x, y: sprite.position.y+128), duration: 1))
    }

    word.remove(at: word.startIndex)
}

let sequenceOfActions = SKAction.sequence([actions])
sprite.run(sequenceOfActions)