Cocos2d iPhone: rotate a sprite with an accelerometer

I am trying to rotate a sprite using an accelerometer. when I lean to the right, I want him to turn slightly to the right, and when I lean to the left, I want him to turn slightly to the left ...

Thanks in advance, Reed

+3
source share
3 answers

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

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

Also make sure your h file has:

@interface myViewName : UIViewController <UIAccelerometerDelegate>

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

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

Then in your .m file in 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 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
}

, , .

, ,

+9

→ >

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..:)

0

Source: https://habr.com/ru/post/1767263/


All Articles