Question

I have a UIImageView that is set to move up and down the screen with the value of the accelerometer, using the following code:

ship.center = CGPointMake(ship.center.x, ship.center.y+shipPosition.y);

Where shipPosition is a CGPoint set in the accelerometerDidAccelerate method using:

shipPosition.y = acceleration.x*60;

Obviously this works fine, it is very simple. I run into trouble when I try to something equally simple, vary the rotation of the image depending on its acceleration. I do this using:

ship.transform = CGAffineTransformMakeRotation(shipPosition.y);

For some reason this causes a very strange thing to happen, in that the image snaps back to its origin every time the main method is called. I can see frames where the image moves to where it should be, but then instantly snaps back.

This problem only happens when I have the rotation line in, commented out it works fine. I have no idea what is going on here, I have done this many times for different apps and i never had such a problem. In fact I copied my code from a different app I created where it works fine.

EDIT:

What really confuses me is when I change the angle of the rotation from the acceleration to the position of the ship using:

ship.transform = CGAffineTransformMakeRotation(ship.center.y/10);

When I do this, the ship actually rotates based on the accelerometer but does not move, which is crazy because a changing ship.center.y means the position of the ship is changing, but it's not!!

Was it helpful?

Solution

You should set the transform of you view back to CGAffineTransformIdentity before you set his center coordinates or frame and after that apply the new transformation.

The frame property returns the transformed coordinates of a view if it is transformed and not the true (well actually the transformed are true) coordinates.

Quote from the docs:

Warning: If the transform property is not the identity transform, the value of this property is undefined and therefore should be ignored.


Update/Actual Answer:
Well the actual problem is

shipPosition.y = acceleration.x*60;

Since you set the y pos in accelerometerDidAccelerate.
The acceleration won't remember it's old value. So if you move your device it will get a peak and as you slow down it will decelerate again.

Your ship will be +/-60 at the highest acceleration speed but will be 0 when you stop moving your device and shipPosition.y will be 0.

OTHER TIPS

CGAffineTransformMakeRotation expects angle in radians, not in degrees.

1 radian = M_PI / 180.0 degrees

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top