Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Interactive Animations

Interactive Animations

Check out this article for more details: http://www.objc.io/issue-12/interactive-animations.html

Florian Kugler

May 09, 2014
Tweet

More Decks by Florian Kugler

Other Decks in Programming

Transcript

  1. Problems » Model and presentation layer out of sync »

    Especially: Driving animations directly
  2. Requirements » Recognise user interaction at any time » Sync

    up presentation and model layer » Control animations indirectly
  3. CADisplayLink - (void)setupDisplayLink { self.displayLink = [screen displayLinkWithTarget:self selector:@selector(animationTick:)]; self.displayLink.paused

    = YES; [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; } - (void)animationTick:(CADisplayLink *)displayLink { CFTimeInterval dt = displayLink.duration; // drive your animation ... }
  4. Physics in Code - (void)animationTick:(CFTimeInterval)dt finished:(BOOL *)finished { static const

    float frictionConstant = 20; static const float springConstant = 300; CGFloat time = (CGFloat) dt; // friction force = velocity * friction constant CGPoint frictionForce = CGPointMultiply(self.velocity, frictionConstant); // spring force = (target point - current position) * spring constant CGPoint springVector = CGPointSubtract(self.targetPoint, self.view.center); CGPoint springForce = CGPointMultiply(springVector, springConstant); // force = spring force - friction force CGPoint force = CGPointSubtract(springForce, frictionForce); // velocity = current velocity + force * time / mass self.velocity = CGPointAdd(self.velocity, CGPointMultiply(force, time)); // position = current position + velocity * time self.view.center = CGPointAdd(self.view.center, CGPointMultiply(self.velocity, time)); // stop the animation when it's done... }