How to make simple tilting function on the iPhone

Hi,

I'm trying to create a simple tilt function using the iPhone's accelerometer in Unity. I've looked at a lot samples but can't get it to work the way I want. My App basically has a 2D character. What I'm trying to do is:

//pseudocode if(tiltleft > 0) { //do something }

if(tiltright > 0) { //do something }

Could someone advice me on how to approach this or point me to a good tutorial on accelerometers please?

Thanks in advance,

Hakimo

There's a decent example for multi-dimensional tilt functionality in the iPhone Unity documentation, but I actually just messed around with getting this working in my project last night.

I think we have the same problem - apply the tilt along X to the X coordinate of our character in a 2D plane. Here's how I got it working... This is in C# and is based on the iPhone controls documentation.

public float TiltSpeed = 5.0f;

void FixedUpdate() {
            float tiltAngle = iPhoneInput.acceleration.x;

            tiltAngle *= Time.deltaTime;
            tiltAngle *= TiltSpeed;

            // Move object - Change this to transform.position if you don't have a rigid body on your char.
            rigidbody.AddForce(tiltAngle, 0, 0);

}

Obviously, you need to test this on the device or with Unity Remote. I actually have a script that displays my devices tilt amount onGUI so I can see precisely what kind of X values the device is returning.

As Smorpheus suggested, to use the accelerometer I've got the `Controller.js` from Unity's Roll-a-ball iPhone example: http://unity3d.com/support/resources/example-projects/iphone-examples.html

Maybe it's not exactly what you needed, but I guess it's related enough, a good hint and good to document. It's quite simple and I even simplified it a little:

public float force = 9.8f;

void FixedUpdate ()
{
    dir.x = Input.acceleration.x;
    dir.y = Input.acceleration.y;
    Physics.gravity = dir * force;
}