0

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

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

2 回答 2

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)
于 2016-01-25T15:23:33.350 回答
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 对其进行初始化,然后:

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

如果你想停止这个动作,你可以像这样访问它:

if sprite.actionForKey("aKey") != nil {
            removeActionForKey("aKey")
}
于 2016-01-25T15:24:05.663 回答