[iOS]15パズル(2)
駒の移動にアニメーションを施す。
前回のサンプル・コードでは、駒のフレームに、移動先のマスのフレームを設定していた。これをアニメーションに変更する。
ゲームコントローラで、駒の移動をGamePieceViewのメソッドmoveWithSquare:に変更する。
@implementation GameController
...
- (void)gameBoardViewTouchUp:(GameBoardView *)gameBoardView location:(CGPoint)touchPt taps:(int)taps event:(UIEvent*)event
{
if (self.pieceView) {
GameSquare *square = [self.gameBoardView squareAtPoint:touchPt];
[self.pieceView moveWithSquare:square]; ←変更
}
self.pieceView = nil;
}
...
@end
moveWithSquare:メソッドの処理内容は以下の通り。
@implementation GamePieceView
...
- (void)moveWithSquare:(GameSquare *)square
{
CGRect frame = [square frame];
[self moveFrame:frame];
}
- (void)moveFrame:(CGRect)frame
{
CABasicAnimation *theAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
CGPoint fromPt = self.layer.position;
CGPoint toPt = CGPointMake(frame.origin.x + (frame.size.width / 2.0),
frame.origin.y + (frame.size.height / 2.0));
theAnimation.fromValue = [NSValue valueWithCGPoint:fromPt];
theAnimation.toValue = [NSValue valueWithCGPoint:toPt];
theAnimation.delegate = self;
[self.layer addAnimation:theAnimation forKey:@"animatePosition"];
self.layer.frame = frame;
}
...
@end
ドラッグして指を離すと、アニメーションしてマスに駒がはまるようになったと思う。
ソースコード
GitHubからどうぞ。
https://github.com/murakami/workbook/tree/master/ios/FifteenPuzzle - GitHub
関連情報
実践!iOSで作るゲームアプリ
【Cocoa練習帳】
http://www.bitz.co.jp/weblog/
http://ameblo.jp/bitz/(ミラー・サイト)