如何在动画中设置单个SKTextures的持续时间

时间:2016-01-25 14:44:34

标签: swift sprite-kit swift2 sktexture

我正在尝试为动画中的个人SKTextures设置持续时间。低于armsAtlas纹理图集。我想将upTexture设置为持续1-4秒,然后downTexture持续0.3到1秒。如何为各个纹理设置这些持续时间范围?

let armsAtlas = SKTextureAtlas(named: "arms")
let downTexture = armsAtlas.textureNamed("down")
let upTexture = armsAtlas.textureNamed("up")

2 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点。

您可以使用SKAction延迟在它们之间随机交换......

func setTexture(texture: SKTexture, delay: NSTimeInterval, range: NSTimeInterval) -> SKAction {
    let textureAction = SKAction.setTexture(texture)
    let delayAction = SKAction.waitForDuration(delay, withRange: range)
    return SKAction.sequence([delayAction, textureAction])
}

没有设置动作以在两者之间切换......

let downAction = setTexture(downTexture, delay: 0.65, range: 0.35)
let upAction = setTexture(upTexture, delay: 2.5, range: 1.5)
let sequenceAction = SKAction.sequence([downAction, upAction])
let repeatAction = SKAction.repeatActionForever(sequenceAction)

yourTexturedSprite.runAction(repeatAction)

答案 1 :(得分:1)

你可以使用SKAction序列和它的waitForDuration:withRange:方法,如下所示:

//By default, the sprite is initialized with downTexture
let sprite = SKSpriteNode(texture: downTexture)
sprite.position = CGPoint(x: 200, y: 200)
addChild(sprite)
let sequence = SKAction.sequence([

    SKAction.runBlock({NSLog("Up texture set")}), //Added just for debugging to print a current time
    SKAction.setTexture(upTexture),
    SKAction.waitForDuration(2.5, withRange: 3.0),  //Wait between 1.0 and 4.0 seconds
    SKAction.runBlock({NSLog("Down texture set")}),
    SKAction.setTexture(downTexture),
    SKAction.waitForDuration(0.65, withRange: 0.7),//Wait between 0.3 and 1.0 seconds
    ])

let action = SKAction.repeatActionForever(sequence)

sprite.runAction(action, withKey: "aKey")

这段代码的作用是创建一个精灵,默认情况下用downTexture初始化它:&/ p>

  • 立即将纹理交换到upTexture
  • 等待1到4秒
  • 将纹理交换为downTexture
  • 等待0.3到1秒
  • 永远重复这一切

如果您想停止此操作,可以像这样访问:

if sprite.actionForKey("aKey") != nil {
            removeActionForKey("aKey")
}