Game Development Reference
In-Depth Information
Listing 4-25. CoinsController.m (doSwitch:With:)
-(void)doSwitch:(Coord)coordA With:(Coord)coordB {
[coinsGame swap:coordA With:coordB];
coinViewA = [[coinsView subviews] objectAtIndex:[coinsGame indexForCoord:coordA]];
coinViewB = [[coinsView subviews] objectAtIndex:[coinsGame indexForCoord:coordB]];
for (UIView* coinView in [NSArray arrayWithObjects:coinViewA, coinViewB, nil]){
CABasicAnimation* animScaleDown = [CABasicAnimation animationWithKeyPath:@"transform.
scale"];
[animScaleDown setValue:@"animScaleDown" forKey:@"name"];
animScaleDown.fromValue = [NSNumber numberWithFloat:1.0f];
animScaleDown.toValue = [NSNumber numberWithFloat:0.0f];
animScaleDown.duration = 1.0;
animScaleDown.timingFunction = [CAMediaTimingFunction
functionWithName:kCAMediaTimingFunctionEaseIn];
CABasicAnimation* animScaleUp = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
[animScaleUp setValue:@"animScaleUp" forKey:@"name"];
animScaleUp.fromValue = [NSNumber numberWithFloat:0.0f];
animScaleUp.toValue = [NSNumber numberWithFloat:1.0f];
animScaleUp.duration = 1.0;
animScaleUp.beginTime = CACurrentMediaTime() + 1.0;
animScaleUp.timingFunction = [CAMediaTimingFunction
functionWithName:kCAMediaTimingFunctionEaseOut];
if (coinViewA == coinView){
[animScaleDown setDelegate:self];
[animScaleUp setDelegate:self];
}
[coinView.layer addAnimation:animScaleDown forKey:@"animScaleDown"];
[coinView.layer addAnimation:animScaleUp forKey:@"animScaleUp"];
}
}
The task
doSwitch:With:
is responsible for updating the model and creating the animations. To
update the model, we simply call
swap:With:
on
coinsGame
. To create the animations, we have to
work with a class called
CABasicAnimation
. A
CABasicAnimation
object describes a change in a
CALayer
. A
CALayer
is an object that represents the visual content of a
UIView
.
Up until this point, we have said that a
UIView
provides the content on the screen, and that is still
true, but a
UIView
uses the Core Animation layer to implement how it is drawn. As such, each
UIView
has a
layer
property of type
CALayer
. You need to understand this in order to understand how
CABasicAnimation
works. Looking at Listing 4-25, you can see that a
CABasicAnimation
is created
by specifying a path. In our case, the path is
transform.scale
. This is a path into the
CALayer
object
associated with the
UIView
we wish to animate.