0

I have two methods of achieving the same sprite animation:

  1. An UIImage that animates an array of 6 images using animatedImage(with:duration:).
  2. A UIView with its CALayer’s contents property set to a sprite atlas image—the layer’s contentsRect property is updated via a CADisplayLink. To ensure frame rate independence, I’m accumulating delta time (or displayLink.duration) until an image should change. When the image changes, I subtract the elapsed time needed for one image from the accumulated delta time and the cycle continues.

Both methods work great and look almost identical (if not identical) on my iPhone. However, when running in Simulator, #1 appears to animate at the device speed, while #2 appears to animate noticeably slower.

When comparing the FPS from my device and the simulator, the device averages around 59.9 to 60 FPS, while Simulator shows a constant 60 FPS; this doesn't account for #2 appearing to be noticeably slower.

So, why is #2 slower in Simulator?

Code for #1:

UIImage.animatedImage(with: spriteImages, duration: animationDuration)

Code for #2:

func update(_ seconds: TimeInterval) {
    accumulatedSeconds += seconds

    // `poseDuration` is `animationDuration / 6`.
    guard accumulatedSeconds >= poseDuration else { return }

    switch currentFrame {
    case 6:
        myView.layer.contentsRect = CGRect(x: 0, y: 0, width: width, height: 1)
        currentFrame = 1
    default:
        myView.layer.contentsRect = CGRect(x: width * Double(currentFrame), y: 0, width: width, height: 1)
        currentFrame += 1
    }

    accumulatedSeconds -= poseDuration
}
JWK
  • 3,345
  • 2
  • 19
  • 27

1 Answers1

2

Basically, CADisplayLink doesn't work well in the simulator. Test on a device only.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Appreciate the confirmation, thanks :) Any chance you can elaborate on why it doesn't work well? Just trying to understand what I'm missing. – JWK Jan 10 '17 at 06:07
  • You're not missing anything. Lots of things don't work in the simulator. This is one of them. – matt Jan 10 '17 at 06:15
  • Hah, ok. Do you have any thoughts on why #1 / `animatedImage(with:duration:)` doesn't suffer from any perceivable rendering issues though? It must be using some sort of timer too, right? – JWK Jan 10 '17 at 07:28
  • Totally different mechanism. Animation in general works fine in the simulator. But the display link is hardware based, and there is no hardware in the simulator, so it has to be emulated. – matt Jan 10 '17 at 13:07