Cocos2d iPhone Rotate Sprite using Accelerometer - Stack Overflow

<div class="posterous_bookmarklet_entry">
  > <div>

Hey,

Firs off - in your h file you need to make the following variables:

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

Also ensure that your h file has:

@interface myViewName : UIViewController <UIAccelerometerDelegate>

Then in your .m file just below your imports at the top put:

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

Then in your .m file on your viewDidLoad Function put:

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

also add the following function to your .m file:

-(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 calibrationscurrentRawReading = atan2(accelerationY, accelerationX);float rotation = -RadiansToDegrees(currentRawReading);targetView.transform = CGAffineTransformMakeRotation(-(DegreesToRadians(rotation)));//targetView.transform = CGAffineTransformRotate(targetView.transform, -(rotation * 3)); //if you want easing}

you will have to tweak it slightly based on what view or object you are targeting – but thats pretty much it.

Hope this helps,

Michael

I tried 2 days but not work until I found out it.

Tweet
comments powered byDisqus