我目前正在制作一个 iPhone 应用程序,并且动画会对轻微的震动做出反应,这是我的代码:
static BOOL SJHShaking(UIAcceleration* last, UIAcceleration* current, double threshold) {
double
deltaX = fabs(last.x - current.x),
deltaY = fabs(last.y - current.y),
deltaZ = fabs(last.z - current.z);
return
(deltaX > threshold && deltaY > threshold) ||
(deltaX > threshold && deltaZ > threshold) ||
(deltaY > threshold && deltaZ > threshold);
}
- (id)initWithFrame:(CGRect)frame
{
if (self) {
// Initialization code
}
return self;
}
-(void)awakeFromNib{
[super awakeFromNib];
[UIAccelerometer sharedAccelerometer].delegate = self;
}
- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration
*) acceleration {
if (self.lastAction) {
if (hasBeenShaken && SJHShaking (self.lastAction, acceleration, 0.7)) {
hasBeenShaken = YES;
animation.animationImages= [NSArray arrayWithObjects:
[UIImage imageNamed:@"Frame01.png"],
[UIImage imageNamed:@"Frame02.png"],
[UIImage imageNamed:@"Frame03.png"],
[UIImage imageNamed:@"Frame04.png"],
[UIImage imageNamed:@"Frame05.png"],
[UIImage imageNamed:@"Frame06.png"],
[UIImage imageNamed:@"Frame07.png"],
[UIImage imageNamed:@"Frame08.png"],
[UIImage imageNamed:@"Frame09.png"],
[UIImage imageNamed:@"Frame010.png"],
[UIImage imageNamed:@"Frame011.png"],
[UIImage imageNamed:@"Frame012.png"],
[UIImage imageNamed:@"Frame013.png"],
nil];
[animation setAnimationRepeatCount:1];
animation.animationDuration = 1;
[animation startAnimating];
[self performSelector:@selector(didFinishAnimating) withObject:nil
afterDelay:1.0];
bottle.hidden=YES;
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/champagne
animate.wav", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer2 = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer2.numberOfLoops = 0;
audioPlayer2.volume = 1;
if (audioPlayer2 == nil);
else
[audioPlayer2 play];
[audioPlayer3 stop];
back.hidden = YES;
} else if (hasBeenShaken && !SJHShaking(self.lastAction, acceleration, 0.2)) {
hasBeenShaken = NO;
}
}
self.lastAction = acceleration;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
-(void)dealloc{
[UIAccelerometer sharedAccelerometer].delegate = nil;
}
在同一个视图控制器上,我在动画之前还有另一个页面,现在我需要他们按下“开始”按钮,然后他们可以摇晃,但在他们按下“开始”之前,如果他们摇晃,什么都不会发生。我该怎么做?