2

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

我正在使用 CoreMotion 从设备获取 Pitch、Roll 和 Yaw,但我不明白如何将这些点转换为向上的方向,尤其是当用户旋转设备时。理想情况下,我可以将这 3 个数字转换为一个值,该值将始终告诉我哪条路是向上的,而无需重新学习所有三角学。

我看过 3D 茶壶示例,但它没有帮助,因为这个示例是 2D 的,我不需要倾斜/倾斜。另外,我不想使用指南针/磁力计,因为它需要在 iPod Touch 上运行。

4

2 回答 2

2

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

在此处输入图像描述

所以你只对XY平面感兴趣。加速度计始终测量设备相对于自由落体的加速度。因此,当您在图像上握住设备时,加速度值为 (0, -1, 0)。当您将设备顺时针倾斜 45 度时,该值为 (0.707, -0.707, 0)。您可以通过计算当前加速度值和某个参考轴的点积来获得角度。如果我们使用向上向量,则轴为 (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)。然后按照我的解释计算一个角度。

于 2012-10-21T02:11:09.727 回答
1

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

文件.h

#import <UIKit/UIKit.h>

@interface RotationAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

-(void)orientationChanged;
@end

文件.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.
}
于 2012-10-21T02:01:05.057 回答