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

Posted in Developer Blog | Tagged , , | Leave a comment

Development Blog!

Welcome to my development blog! My name is Andrew, the developer at Slamdunk Software. I’ll be posting tips and code samples for iPhone, iPad and Android development.

I’ve had a lot of help along the way from the development community whilst developing our first few apps Techitot Pets for iPhone and Android and Landlubbers for iPhone and Android,  so here’s my chance to give something back.

I’ve developed for iOS with Objective-C and X-Code and also C# .Net with MonoTouch. For Android I used Java and Eclipse.

Thanks for checking out my Development Blog :)

Andrew.

 

Posted in Developer Blog | Leave a comment