2010-06-30 3 views
1

iPad 용 cocos2d에서 흔들림을 감지하고 싶습니다.cocos2d에서 악수 이벤트를 감지하는 방법은 무엇입니까?

유망한 기사를 찾았지만 구현하려했지만 실패했습니다. http://www.softvelopment.com/index.php/blogs/2010/03/19/3-adding-shake-recongnition-to-cocos2d-iphone-library-

특히 청취자를 어디에 두어야하는지 잘 모르겠습니다. 또한, cocos2d를 사용하여 iPad가 흔들림을 감지하도록하는 다른 좋은 방법이 있습니까?

답변

2

다음 코드가 도움이 될 수 있습니다. 나는 그것을 잠시 뒤로 찾았고 (기억하지 않고) 그것을 청소했다. didAccelerate의 값을 현재 0.8과 0.2로 조정하여 흔들리는 민감도와 다시 흔들릴 수있는 장치의 안정성을 정의 할 수 있습니다.

헤더

@protocol ShakeHelperDelegate 
-(void) onShake; 
@end 

@interface ShakeHelper : NSObject <UIAccelerometerDelegate> 
{ 
    BOOL histeresisExcited; 
    UIAcceleration* lastAcceleration; 

    NSObject<ShakeHelperDelegate>* delegate; 
} 

+(id) shakeHelperWithDelegate:(NSObject<ShakeHelperDelegate>*)del; 
-(id) initShakeHelperWithDelegate:(NSObject<ShakeHelperDelegate>*)del; 

@end 

구현

#import "ShakeHelper.h" 


@interface ShakeHelper (Private) 
@end 

@implementation ShakeHelper 

// Ensures the shake is strong enough on at least two axes before declaring it a shake. 
// "Strong enough" means "greater than a client-supplied threshold" in G's. 
static BOOL AccelerationIsShaking(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) shakeHelperWithDelegate:(NSObject<ShakeHelperDelegate>*)del 
{ 
    return [[[self alloc] initShakeHelperWithDelegate:del] autorelease]; 
} 

-(id) initShakeHelperWithDelegate:(NSObject<ShakeHelperDelegate>*)del 
{ 
    if ((self = [super init])) 
    { 
     delegate = del; 
     [UIAccelerometer sharedAccelerometer].delegate = self; 
    } 

    return self; 
} 

-(void) accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration 
{ 
    if (lastAcceleration) 
    { 
     if (!histeresisExcited && AccelerationIsShaking(lastAcceleration, acceleration, 0.8)) 
     { 
      histeresisExcited = YES; 

      [delegate onShake]; 
     } 
     else if (histeresisExcited && !AccelerationIsShaking(lastAcceleration, acceleration, 0.2)) 
     { 
      histeresisExcited = NO; 
     } 
    } 

    [lastAcceleration release]; 
    lastAcceleration = [acceleration retain]; 
} 

-(void) dealloc 
{ 
    CCLOG(@"dealloc %@", self); 

    [UIAccelerometer sharedAccelerometer].delegate = nil; 
    [lastAcceleration release]; 
    [super dealloc]; 
} 

@end 

이처럼 사용

[ShakeHelper shakeHelperWithDelegate:self]; 

는 분명히 자기 객체가 ShakeHelperDelegate 의정서를 이행 할 필요가있다. 쉐이크가 감지 될 때마다 onShake 메시지가 대리자 객체로 전송됩니다.

관련 문제