Pregunta

How can I update x and y position of an object from the amount of tilt?

I'm trying to update the x and y position of my _bg object, based on the amount of a tilt movement.

Also, if the device is put down on a table, the position should go back to it's original position;

I'm trying to do something like this:

- (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);
}

Problem is that the object doesn't stop moving, ever!

Thank you!

¿Fue útil?

Solución

A rate is the amount of change per unit time. Thus you are setting the coordinates relative to how quickly the device is moving, not its actual offset. You may want to look into its attitude (its actual offset from an arbitrary frame of reference). The documentation is here.

Otros consejos

This might be helpful. Not sure though based on the limited data available from the question. You should probably also switch to using absolute position/rotation, not relative change between frames.

Simply set a minimum threshold. This will prevent minute movements from showing as updates:

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);

I think you are making mistake in setting new center. Try this :

- (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);
}

By the way, your application will keep receiving gyro updates even when you put device on table, because table's slope is not guaranteed to be 0 degree.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top