目标c-iPhone加速度计改变灵敏度-可可触摸



你好我想改变灵敏度,当用户移动设备时。目前它还不是很敏感,我相信它已经违约了。我希望它更灵敏,这样当用户稍微摇晃手机时,声音就会播放。

这是代码

感谢

- (BOOL)canBecomeFirstResponder
{
    return YES;
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if(motion == UIEventSubtypeMotionShake)
    {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"whip" ofType:@"wav"];
        if (theAudio) [theAudio release];
        NSError *error = nil;
        theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
        if (error)
            NSLog(@"%@",[error localizedDescription]);
        theAudio.delegate = self;
        [theAudio play];    
    }
}

首先,确保您的接口采用UIAcceleratobeterDelegate协议。

@interface MainViewController : UIViewController <UIAccelerometerDelegate>

现在在您的实施中:

//get the accelerometer
self.accelerometer = [UIAccelerometer sharedAccelerometer];
self.accelerometer.updateInterval = .1;
self.accelerometer.delegate = self;

实施委托方法:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration 
{
  float x = acceleration.x;
  float y = acceleration.y;
  float b = acceleration.z;
  // here you can write simple change threshold logic
  // so you can call trigger your method if you detect the movement you're after
}

加速度计为x、y和z返回的值将始终是介于-1.0和正1.0之间的浮点值。您应该调用NSLog并将x、y和z值输出到控制台,以便了解它们的含义。然后你可以开发一种简单的方法来检测运动。

您无法更改shake事件的工作方式。如果你需要不同的东西,你必须根据[UIAcclerometer sharedAcclerometer]给你的x/y/z力编写自己的抖动检测代码;如果您将sharedAcclerometer的委托设置为您的类,则可以获得加速度计的加速度计:didAccleremeter:委托回调。

如果您试图重新创建抖动手势,请记住以下几点:

抖动是指在一个方向上的运动,然后是在通常相反的方向上的移动。这意味着你必须跟踪你以前的加速度向量,这样你就知道它们什么时候会改变。为了不让你错过它,你必须经常从加速度计上采样。

CGFloat samplesPerSecond = 30;
[[UIAccelerometer sharedAccelerometer] setDelegate: self];
[[UIAccelerometer sharedAccelerometer] setUpdateInterval: 1.0 / samplesPerSecond]; 

然后在您的代表回拨中:

- (void) accelerometer: (UIAccelerometer *) accelerometer didAccelerate: (UIAcceleration *) acceleration {
  // TODO add this acceleration to a list of accelerations and keep the most recent (perhaps 30)
  // TODO analyze accelerations and determine if a direction change occurred
  // TODO if it did, then a shake occurred!  Clear the list of accelerations and perform your action
}

最新更新