如何从倾斜量更新x和y位置?

时间:2013-06-20 15:25:27

标签: ios objective-c core-motion

如何从倾斜量 更新对象的x和y位置

我正在尝试根据倾斜动作的数量更新 _bg 对象的 x 和y位置。

此外,如果将设备放在桌子上,该位置应该回到原来的位置;

我正在尝试做这样的事情:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    _motionManager = [[CMMotionManager alloc] init];

    [_motionManager startGyroUpdates];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1/30
                                              target:self
                                            selector:@selector(updateGyro)
                                            userInfo:nil repeats:YES];
}



- (void)updateFromGyro
{
    self.x += _motionManager.gyroData.rotationRate.x;
    self.y += _motionManager.gyroData.rotationRate.y;

    _bg.center = CGPointMake(self.x, self.y);
}

问题是对象永远不会停止移动!

谢谢!

3 个答案:

答案 0 :(得分:0)

这可能会有所帮助。但不确定是基于该问题提供的有限数据。您可能还应该切换到使用绝对位置/旋转,而不是帧之间的相对变化。

只需设置最低阈值即可。这样可以防止分钟动作显示为更新:

if( _motionManager.gyroData.rotationRate.x > ROTATION_MIN )
{
    self.x += _motionManager.gyroData.rotationRate.x;
}
if( _motionManager.gyroData.rotationRate.y > ROTATION_MIN )
{
    self.y += _motionManager.gyroData.rotationRate.y;
}
_bg.center = CGPointMake(self.x, self.y);

答案 1 :(得分:0)

费率是每单位时间的变化量。因此,您要设置相对于设备移动快速的坐标,而不是其实际偏移。您可能希望查看其attitude(它与任意参考帧的实际偏移量)。文档为here

答案 2 :(得分:0)

我认为你在设置新中心时犯了错误。试试这个:

- (void)updateFromGyro
{
    self.x = _bg.center.x + _motionManager.gyroData.rotationRate.x;
    self.y = _bg.center.y + _motionManager.gyroData.rotationRate.y;

    _bg.center = CGPointMake(self.x, self.y);
}

顺便说一句,即使您将设备放在桌面上,您的应用程序也会继续接收陀螺仪更新,因为表格的斜率不能保证为0度。