Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode iPhone accelerometer image

I'm French so excuse me for my English. So I use an accelerometer, but in my code the accelerometer works for a view and not for an image. What I want to do is to use this accelerometer for an image instead of a view. How can I do this? Here is the code:

#define CONST_fps 100.
#define CONST_map_shift 0.01
#define kFilteringFactor 0.1
UIAccelerationValue rollingX, rollingY, rollingZ;

@implementation MapViewRotationViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // accelerometer settings
    [[UIAccelerometer sharedAccelerometer] setDelegate:self];
    [[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / CONST_fps)];
}

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor));

    rollingY = (acceleration.y * kFilteringFactor) + (rollingY * (1.0 - kFilteringFactor));

    rollingZ = (acceleration.z * kFilteringFactor) + (rollingZ * (1.0 - kFilteringFactor));

    float accelX = acceleration.x - rollingX;
    float accelY = acceleration.y - rollingY;
    float accelZ = acceleration.z - rollingZ;

    static CGFloat ZZ = 0.;
    CGFloat z = (atan2(rollingX, rollingY) + M_PI);

    if (fabsf(ZZ - z) > CONST_map_shift)
    {
        viewToRotate.layer.transform = CATransform3DMakeRotation(ZZ=z, 0., 0., 1.);
    }
}

@end
like image 430
arvin Arabi Avatar asked Nov 05 '22 23:11

arvin Arabi


1 Answers

You don't need to have a view as callback instead you can choose any class to conform to protocol UIAccelerometerDelegate. Just declare your class in the header file as

@interface MyClass : NSObject <UIAccelerometerDelegate> {
  // my members
}

In MyClass.m you have to implement method

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
  // do what you like
}

But if you are not forced to support iOS version 3.x, you should consider using CoreMotion API. See Event Handling Guide for iOS / Motion Events for more information and samples.

like image 80
Kay Avatar answered Nov 10 '22 19:11

Kay