Prachi Joshi
Prachi Joshi

Reputation: 375

unity 3d rotate the gameobject according to accelerometer

I want to make a game like temple run. I need to rotate the platform of my player according to the how much I tilt the device. I am trying the accelerometer but I could not get the game object tilted. Please guide me. Thanks

This is my code I was using the code in comments previously now im trying to use the code out of the comments

public class tilt : MonoBehaviour {
Vector3 dir;
float movespeed;
bool istilt;
// Use this for initialization
void Start () {
    dir=Vector3.zero;
    movespeed=10.0f;
    istilt=true;

}

// Update is called once per frame
void FixedUpdate()
{
    //dir.x=-Input.acceleration.y;
    //transform.Translate(dir.x,0,0);
    //transform.Translate(Input.acceleration.x, 0, -Input.acceleration.z);
    //Vector3 vec = Physics.gravity;
    /*vec.x = -Physics.gravity.z;
    vec.z = Physics.gravity.x;
    vec.y = 0;
    transform.rotation = Quaternion.Euler(vec);*/
    /*movespeed=-Input.acceleration.y;

    transform.Rotate(Vector3.up*movespeed*5.0f); 
*/float zmovment = Input.GetAxis("Horizontal");//-Input.acceleration.y;
    float xmovment = Input.GetAxis("Vertical");//-Input.acceleration.x;
    Vector3 dir = new Vector3(xmovment,0,zmovment);

    Vector3 tgravity =new Vector3(zmovment*2.0f,-15,xmovment*2.0f);
    Physics.gravity= tgravity;//new Vector3(zmovment*speed,gravity,xmovment*speed);
    Vector3 vec = Physics.gravity;
    vec.x = -Physics.gravity.z;
    vec.z = Physics.gravity.x;
    vec.y = 0;
    transform.rotation = Quaternion.Euler(vec);
}

}

Upvotes: 2

Views: 5703

Answers (1)

Imapler
Imapler

Reputation: 1422

One way of doing it to use gravity as the normal of the platform like this

transform.rotation = Quaternion.LookRotation(Input.acceleration, Vector3.up);

You might have to switch the axis on the acceleration so that down is forward depending on what is forward on your platform. This is my guess

Vector3 forward = new Vector3(-Input.acceleration.y, Input.acceleration.x, Input.acceleration.z);
transform.rotation = Quaternion.LookRotation(forward, Vector3.up);

Also note that this will only be correct when the device is still. Movement from side to side will cause a rotation on your platform which might be undesirable.

Upvotes: 3

Related Questions