タッチしたところに花火があがるエフェクトを出すサンプル
(Xcode の iOS6 Simulator で試してます。)
ポイント
花火っぽく見せるために、
小さなViewを時間差で円の上に表示し、
微小時間後に削除する
サンプルコード
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
// 夜っぽく
self.view.backgroundColor = [UIColor blackColor];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *t = [touches anyObject];
CGPoint touchPoint = [t locationInView:self.view];
// タッチしたところに花火。
UIView *fire = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
fire.center = CGPointMake(touchPoint.x, self.view.frame.size.height);
fire.backgroundColor = [UIColor orangeColor];
[self.view addSubview:fire];
[UIView animateWithDuration:1.0 animations:^{
// 花火をあげる
fire.center = CGPointMake(touchPoint.x, touchPoint.y);
} completion:^(BOOL finished) {
// 上げてる火を消す
[fire removeFromSuperview];
// 花火を咲かせる
[self fire:touchPoint];
}];
}
// 花火のメイン処理
– (void)fire:(CGPoint)center
{
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
v.center = center;
[self.view addSubview:v];
for (int i=0; i<5; i++) {
// 花火の火を時間差で表示
float time = 0.2 * i * NSEC_PER_SEC;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, time), dispatch_get_main_queue(), ^{
CGPoint o = [v convertPoint:center fromView:self.view];
[self circleInView:v center:o r:i * 10];
});
}
// 花火終了後に実行
float time = 2.5 * NSEC_PER_SEC;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, time), dispatch_get_main_queue(), ^{
//花火のViewを全部消す
[v removeFromSuperview];
});
}
– (void)circleInView:(UIView*)v center:(CGPoint)center r:(float)r
{
// 花火の輪を作る
for (int i=0; i< 4 * M_PI; i++) {
UIView *piece = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 5)];
float x = center.x + r * sinf(i * M_PI / 4);
float y = center.y + r * cosf(i * M_PI / 4);
piece.center = CGPointMake(x, y);
piece.backgroundColor = [UIColor redColor];
[v addSubview:piece];
[UIView animateWithDuration:0.5 animations:^{
piece.alpha = 0;
}];
}
}
@end
tengusa64
ブログを拝見してすごい人がいるな、とつくづく感じ入っています。
じつは、このプログラムを拝借してゲームのフィナーレを作りました。
http://ameblo.jp/oldamebaman/entry-11447329159.html
事前にお伺いを立てなければならないところでしょうが、無断で借用させていただきました。
今から他のブログも勉強させていただきます。
それにしてもすごい人ですね。
mizu
iOSはまだ一年生なので、
筋トレのつもりで、暇を見つけては作っています。