2010-09-29 53 views

回答

9

杉杉關閉 - 在您的H文件,你需要做以下變量:

UIAccelerationValue accelerationX; 
UIAccelerationValue accelerationY; 
float currentRawReading; 
float calibrationOffset; 

還要確保你的h文件有:

@interface myViewName : UIViewController <UIAccelerometerDelegate> 

然後在你的.m文件中j烏斯你進口在頂部下面放:

#define kFilteringFactor 0.05 
CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI/180;}; 
CGFloat RadiansToDegrees(CGFloat radians) {return radians * 180/M_PI;}; 

然後在把你的viewDidLoad函數的.m文件:

UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer]; 
accel.delegate = self; 
accel.updateInterval = 1.0f/60.0f; 

也將添加以下功能,您的.m文件:

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

accelerationX = acceleration.x * kFilteringFactor + accelerationX * (1.0 - kFilteringFactor); 
accelerationY = acceleration.y * kFilteringFactor + accelerationY * (1.0 - kFilteringFactor); 

// keep the raw reading, to use during calibrations 
currentRawReading = atan2(accelerationY, accelerationX); 

float rotation = -RadiansToDegrees(currentRawReading); 

targetView.transform = CGAffineTransformMakeRotation(-(DegreesToRadians(rotation))); 
//targetView.transform = CGAffineTransformRotate(targetView.transform, -(rotation * 3)); //if you want easing 
} 

你將不得不稍微調整它基於你的目標是什麼視圖或對象 - 但這就是它。

希望這有助於

邁克爾

+0

請注意,這是針對普通的iOS應用程序。對於cocos2d,所有CCLayer對象都已符合UIAccelerometerDelegate,您只需設置node.isAccelerometerEnabled = YES,然後像往常一樣創建加速度計:DidAccelerate:方法。請參閱http://www.cocos2d-iphone.org/wiki/doku.php/tips%3ausing_accelerometer_for_sprite_movement然而,您應該仍然可以像Michael O'Brien所示的那樣濾除加速計讀數。有關詳情,請參閱http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/MotionEvents/MotionEvents.html – aiham 2012-02-02 00:55:47

0

在加速度計的委託功能只寫代碼 - >>

float angleRadians = atanf((float)X_Position/(float)Y_Position); 
float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians); 
float cocosAngle = 1 * angleDegrees; 
sprite.rotation = cocosAngle; 

和精靈將得到旋轉到所需角度的變化X_position,Y_Position和angle的值。

Njoy .. :)