我正在尝试使用加速度计旋转精灵。当我向右倾斜时,我希望他向右稍微旋转;当我向左倾斜时,我希望他向左稍微旋转...
提前致谢,
芦苇
最佳答案
首先-在您的h文件中,您需要执行以下变量:
UIAccelerationValue accelerationX;
UIAccelerationValue accelerationY;
float currentRawReading;
float calibrationOffset;
还要确保您的h文件具有:
@interface myViewName : UIViewController <UIAccelerometerDelegate>
然后在您的.m文件中,位于您导入文件顶部下方的位置:
#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
}
您将必须根据要定位的视图或对象进行微调,但这仅是大部分。
希望这可以帮助,
麦可