使用Core Motion和CATransform3D旋转图像

时间:2011-11-09 20:12:08

标签: iphone objective-c ios

我正在尝试设计一个应用程序,让它看起来好像你可以环顾一个对象。我已经走得很远了,但是我无法弄清楚如何使物体像空气一样漂浮在空中(而不是平坦的地面)。

这是我的代码:

CMMotionManager *motionManager = [[CMMotionManager alloc] init];
[motionManager setDeviceMotionUpdateInterval:0.1];

CMDeviceMotionHandler  motionHandler = ^ (CMDeviceMotion *motion, NSError *error) 
{
    [xLabel setText:[NSString stringWithFormat:@"X: %f, Yaw: %f", motion.userAcceleration.x, motion.attitude.yaw]];
    [yLabel setText:[NSString stringWithFormat:@"Y: %f, Pitch: %f", motion.userAcceleration.y, motion.attitude.pitch]];
    [zLabel setText:[NSString stringWithFormat:@"Z: %f, Roll: %f", motion.userAcceleration.z, motion.attitude.roll]];

    CATransform3D transform;
    transform = CATransform3DMakeRotation(motion.attitude.pitch, 1, 0, 0);
    transform = CATransform3DRotate(transform, motion.attitude.roll, 0, 1, 0);
    transform = CATransform3DRotate(transform, motion.attitude.yaw, 0, 0, 1);

    myView.layer.sublayerTransform = transform;
    //[myImage setNeedsDisplay];
};

[motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXTrueNorthZVertical toQueue:[NSOperationQueue currentQueue] withHandler:motionHandler];

这会让它看起来像桌子上的图片是扁平的,但它应该看起来像是挂在墙上。关于如何做到的任何想法?

1 个答案:

答案 0 :(得分:1)

如果它看起来很平坦,您只需要将正确的旋转添加到俯仰旋转代码,以使其默认直立。尝试将音高旋转更改为下面的代码

transform = CATransform3DMakeRotation(motion.attitude.pitch + M_PI_2, 1, 0, 0);

如果颠倒了,请尝试减法。