代码功能:晃动手机播放动画,晃动技术达到4触发事件,如果没有触发事件,1秒后重置 并停止动画。
动画:
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"ballotTu.plist"];
ballotTu = [CCSprite spriteWithSpriteFrameName:@"ballot2.png"];
ballotTu.position = ccp(winSize.width/2, winSize.height/480*300);
[self addChild:ballotTu z:1 tag:10];
NSMutableArray *walkAnimFrames = [[NSMutableArray alloc]init];;
for(int i = 1; i <= 3; ++i) {
[walkAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"ballot%d.png", i]]];
}
CCAnimation *walkAnim = [CCAnimation animationWithFrames:walkAnimFrames delay:0.1f];
walkAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:walkAnim restoreOriginalFrame:NO]];
ballotTu=(CCSprite *)[self getChildByTag:10];
[ballotTu runAction:walkAction];
[walkAnimFrames release];
功能事件:
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
static NSInteger shakeCount=0;
static NSDate *shakeStart;
NSDate *now=[[NSDate alloc] init];
// 摇晃 2秒内
NSDate *checkDate=[[NSDate alloc] initWithTimeInterval:1.0f sinceDate:shakeStart];
//超过2秒 重计算晃动次数
if ([now compare:checkDate]==NSOrderedDescending||shakeStart==nil){
ballotTu=(CCSprite *)[self getChildByTag:10];
[ballotTu stopAllActions];
if (!isStop) {
progressTimer.percentage=0;
}
shakeCount=0;
[shakeStart release];
shakeStart=[[NSDate alloc] init];
}
[now release];
[checkDate release];
// 三轴摇晃的G力超过2则 列入计次
if (fabsf(acceleration.x)>2.0 || fabsf(acceleration.y)>2.0 || fabsf(acceleration.z)>2.0){
NSLog(@"晃动了。。。。。。。");
shakeCount++;
if (!isStop) {
progressTimer.percentage=progressTimer.percentage+5;
NSLog(@"监听 诚心 值:%f",progressTimer.percentage);
if (progressTimer.percentage>100) {
progressTimer.percentage=100;
}
//晃动签筒
NSMutableArray *walkAnimFrames = [[NSMutableArray alloc]init];;
for(int i = 1; i <= 3; ++i) {
[walkAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"ballot%d.png", i]]];
}
CCAnimation *walkAnim = [CCAnimation animationWithFrames:walkAnimFrames delay:0.1f];
walkAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:walkAnim restoreOriginalFrame:NO]];
ballotTu=(CCSprite *)[self getChildByTag:10];
[ballotTu runAction:walkAction];
[walkAnimFrames release];
}else{
NSLog(@"is stop : %d",isStop);
[self stopAllActions];
progressTimer.percentage=nowValue;
}
//2秒内侦测到4次则判定为Shake摇晃手机
if (shakeCount>5){
shakeCount=0;
[shakeStart release];
shakeStart=[[NSDate alloc] init];
//震动了
NSLog(@"手机震动了");
float ranadom=CCRANDOM_0_1();
NSLog(@"this is radom:: %f",ranadom);
if (ranadom >0.4) {
isStop=YES;
nowValue=progressTimer.percentage;
[self ballot];
}
}
return;
}
}