How to get iPhone/iPad angle from accelerometer using MonoTouch

For a new game that we’re working on at Slamdunk Software, I needed to be able to work out the angle that the iPhone/iPad was on.

It was quite simple to get it working in MonoTouch. I created a new view controller with xib and in the Initialize() method I put the following code…

void Initialize ()
{
     UIAccelerometer.SharedAccelerometer.UpdateInterval = 0.05;

     UIAccelerometer.SharedAccelerometer.Acceleration +=
                delegate(object sender, UIAccelerometerEventArgs e)
     {
          double accelerationX = e.Acceleration.X;
          double accelerationY = - e.Acceleration.Y;
          double currentRawReading = Math.Atan2(accelerationY, accelerationX);

          angle = RadiansToDegrees(currentRawReading);

          // Display Angle
          lblAngle.Text = angle.ToString();
      };
}

private double RadiansToDegrees(double radians)
{
	return radians * 180/Math.PI;
}

So there you have it! Enjoy

This entry was posted in Developer Blog and tagged , , . Bookmark the permalink.

Leave a Reply