Created
May 22, 2012 13:32
-
-
Save odrobnik/2769082 to your computer and use it in GitHub Desktop.
A physical jump/bounce animation as CAKeyframeAnimation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (CAKeyframeAnimation *)jumpAnimation | |
{ | |
// these three values are subject to experimentation | |
CGFloat initialMomentum = 150.0f; // positive is upwards, per sec | |
CGFloat gravityConstant = 250.0f; // downwards pull per sec | |
CGFloat dampeningFactorPerBounce = 0.6; // percent of rebound | |
// internal values for the calculation | |
CGFloat momentum = initialMomentum; // momentum starts with initial value | |
CGFloat positionOffset = 0; // we begin at the original position | |
CGFloat slicesPerSecond = 60.0f; // how many values per second to calculate | |
CGFloat lowerMomentumCutoff = 5.0f; // below this upward momentum animation ends | |
CGFloat duration = 0; | |
NSMutableArray *values = [NSMutableArray array]; | |
do | |
{ | |
duration += 1.0f/slicesPerSecond; | |
positionOffset+=momentum/slicesPerSecond; | |
if (positionOffset<0) | |
{ | |
positionOffset=0; | |
momentum=-momentum*dampeningFactorPerBounce; | |
} | |
// gravity pulls the momentum down | |
momentum -= gravityConstant/slicesPerSecond; | |
CATransform3D transform = CATransform3DMakeTranslation(0, -positionOffset, 0); | |
[values addObject:[NSValue valueWithCATransform3D:transform]]; | |
} while (!(positionOffset==0 && momentum < lowerMomentumCutoff)); | |
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"]; | |
animation.repeatCount = 1; | |
animation.duration = duration; | |
animation.fillMode = kCAFillModeForwards; | |
animation.values = values; | |
animation.removedOnCompletion = YES; // final stage is equal to starting stage | |
animation.autoreverses = NO; | |
return animation; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment