iPhone的方向 – 如何找出哪个方向是?

我试图在屏幕上总是面向“向上”绘制2D图像。 如果用户正在旋转他们的手机,我想确保我的2D对象不随设备旋转; 它应该总是“站立”。 我想补偿用户向左或向右倾斜,而不是倾斜或向自己倾斜。

我正在使用CoreMotion从设备中获取音调,滚动和偏航,但我不明白如何将点转换为方向,特别是在用户旋转设备时。 理想情况下,我可以将这3个数字转换成一个单独的值,这个值总是能告诉我哪一个方法已经启动,而不必重新学习所有的三angular函数。

我已经看了3D茶壶的例子,但它并没有帮助,因为这个例子是二维,我不需要倾斜/朝着倾斜。 另外,我不想使用指南针/磁力计,因为这需要在iPod Touch上运行。

看图像,以更好地理解我在说什么:

在这里输入图像说明

所以你只对XY平面感兴趣。 加速度计总是测量设备相对于自由落体的加速度。 所以当你拿着设备时,它的加速度值是(0,-1,0)。 当您将设备顺时针倾斜45度时,该值为(0.707,-0.707,0)。 您可以通过计算当前加速度值和某个参考轴的点积得到angular度。 如果我们正在使用一个向上的轴是(0,1,0)。 所以点积是

0*0.707 - 1*0.707 + 0*0 = -0.707 

这正是acos(-0.707)= 45度。 所以如果你想让图像保持静止,你需要在背面旋转它,即在XY平面-45度。 如果你想忽略Z值,那么你只需要X轴和Y轴:(X_ACCEL,Y_ACCEL,0)。 你需要重新规范化这个向量(它必须给出1的大小)。 然后按照我的解释计算一个angular度。

苹果为此提供了一个观察者。 这是一个例子。

File.h

 #import <UIKit/UIKit.h> @interface RotationAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; -(void)orientationChanged; @end 

File.m

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. //Get the device object UIDevice *device = [UIDevice currentDevice]; //Tell it to start monitoring rthe accelermeter for orientation [device beginGeneratingDeviceOrientationNotifications]; //Get the notification center for the app NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; //Add yourself an observer [nc addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:device]; HeavyViewController *hvc = [[HeavyViewController alloc] init]; [[self window] setRootViewController:hvc]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; } - (void)orientationChanged:(NSNotification *)note { NSLog(@"OrientationChanged: %d", [[note object] orientation]); //You can use this method to change your shape. }