0

I'm trying to animate something that spins / left to right, but whenever I call spinLeft() or spinRight() then the animation always starts from frame 0.

In other words, I want to be able to say spin something 4 out of 10 frames, stop, then spin in the opposite direction, FROM frame 4. Right now, it resets to frame 0.

var textures = [SKTexture]() // Loaded with 10 images later on.
var sprite = SKSpriteNode()

func spinLeft() {
  let action = SKAction.repeatForever(.animate(with: textures, timePerFrame: 0.1))
  sprite.run(action)
}

func spinRight() {
  let action = SKAction.repeatForever(.animate(with: textures, timePerFrame: 0.1)).reversed()
  sprite.run(action)
}
Fluidity
  • 3,985
  • 1
  • 13
  • 34

1 Answers1

0

You could do this (Syntax may be a little off, but you get the point):

The key here is the .index(of: ... ) which will get you the index.

func spinUp() {
    let index = textures.index(of: sprite.texture)
    if index == textures.count - 1 {
        sprite.texture = textures[0]
    }
    else {
        sprite.texture =  textures[index + 1]   
    }
}

func spinDown() {
    let index = textures.index(of: sprite.texture)
    if index == 0 {
        sprite.texture = textures[textures.count - 1]
    }
    else {
        sprite.texture =  textures[index - 1]   
    }
}

func changeImage(_ isUp: Bool, _ amountOfTime: CGFloat) {
    let wait = SKAction.wait(duration: amountOfTime)
    if isUp {
        run(wait) {
            self.imageUp()
        }
    }
    else {
        run(wait) {
            self.imageDown()
        }
    }
}

If you use something like a swipe gesture recognizer, you can use it's direction to set the isUp Bool value and the velocity of that swipe for the amountOfTime for the changeImage function.

The changeImage will only change the image once, so you will need to handle this somewhere else, or create another function if you want it to continuously spin or die off eventually.

Hope this helps!

Discoveringmypath
  • 1,049
  • 9
  • 23
  • this was great! Here is my version of your implementation: https://stackoverflow.com/questions/44725841/360-degrees-spinnable-object-from-a-photographed-real-object/44792902#44792902 – Fluidity Jun 28 '17 at 04:50