Cocos2d摇/加速度计问题

时间:2011-01-08 02:40:09

标签: iphone ios cocos2d-iphone shake uiaccelerometer

所以我有点背景故事。我想实现一个粒子效果和声音效果,当用户摇动他们的iDevice时,它们持续约3秒左右。但第一个问题是在UIEvent for shake的构建拒绝工作时到达。因此,我接受了一些Cocos老手的建议,只是使用一些脚本将“暴力”加速计输入作为震动。到目前为止工作得很好。

问题在于,如果你继续摇晃它只是一遍又一遍地叠加粒子和声音。现在这不是那么大的交易,除非它发生,即使你小心尝试而不是这样做。所以我希望做的是在粒子效果/声音效果开始时禁用加速度计,然后在它们完成后立即重新启用它。现在我不知道我是否应该按计划,NStimer或其他功能这样做。我对所有建议持开放态度。这是我目前的“摇动”代码。

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

    const float violence = 1;
    static BOOL beenhere;
    BOOL shake = FALSE;

    if (beenhere) return;
    beenhere = TRUE;
    if (acceleration.x > violence * 1.5 || acceleration.x < (-1.5* violence))
        shake = TRUE;
    if (acceleration.y > violence * 2 || acceleration.y < (-2 * violence))
        shake = TRUE;
    if (acceleration.z > violence * 3 || acceleration.z < (-3 * violence))
        shake = TRUE;
    if (shake) {
        id particleSystem = [CCParticleSystemQuad particleWithFile:@"particle.plist"];
        [self addChild: particleSystem];

    // Super simple Audio playback for sound effects!

        [[SimpleAudioEngine sharedEngine] playEffect:@"Sound.mp3"];
        shake = FALSE;
    }

    beenhere = FALSE;
}

2 个答案:

答案 0 :(得分:1)

UIAcceleration有一个timestamp属性。我会修改你的代码,以保存静态变量(可能是static NSTimeInterval timestampOfLastShake?)中成功摇动的当前时间戳。然后将if (shake)修改为if (shake && acceleration.timestamp - 3.0f >= timestampOfLastShake)

结果代码:

  static NSTimeInterval timestampOfLastShake = 0.0f;
  if (shake && acceleration.timestamp - 3.0f >= timestampOfLastShake ) {
        timestampOfLastShake = acceleration.timestamp;
        id particleSystem = [CCParticleSystemQuad particleWithFile:@"particle.plist"];
        [self addChild: particleSystem];

    // Super simple Audio playback for sound effects!

        [[SimpleAudioEngine sharedEngine] playEffect:@"Sound.mp3"];
        shake = FALSE;
    }

答案 1 :(得分:0)

您意识到您正在进行单轴加速度检查,并且您无法确保重复加速(即抖动)。换句话说,如果你放弃手机,你的代码就会认为是有人晃动设备几次(这就是震动)并且每秒发射很多次。因此,要么根据时间应用多轴检查,要么只使用摇动UIEvent。您需要做的只是在您的UIView(或更好的UIWindow)中,实现- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event以确保视图成为第一响应者。这将照顾所有加速度过滤等,并且应用程序不会受到所有加速噪音的轰击(您可以将手机放在桌面上,并且不会将其误认为是摇晃)。

转到此处获取文档:http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/MotionEvents/MotionEvents.html

或者:

- (BOOL)canBecomeFirstResponder {
    return YES;
}

// Now call [self becomeFirstResponder]; somewhere, say in viewDidAppear of the controller.   

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{

}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
     if (event.subtype == UIEventSubtypeMotionShake) {
    // You've got a shake, do something
     }
}

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{

}