- Home /
How to rotate an object to face the direction of the accelerometer in 2D
So I have a player object that I am moving according to the accelerometer with this code:
transform.Translate(Input.acceleration.x * speed, Input.acceleration.y * speed, 0);
I want it to rotate to the direction that it is travelling, I can't do this with a vector3 because I'm not using one for the movement. The basic idea would be for the player to tilt the screen left (in landscape) and for the player object to rotate so that the front of the object also faced left. I have been looking for ways to do this for a while now but I'm still stuck. Any help is appreciated :)
You are definitely using Vector3 for movement. tranform.Translate is based on Vector3 and you have given x,y,z parameters for it in your code. Anyway, you can also rotate the player the same way. Try this-
if(Input.acceleration.x > 0){
transform.rotation = Quaternion.Euler (yourXRotation, yourYRotation, yourZRotation);
} else if (Input.acceleration.y > 0){
transform.rotation = Quaternion.Euler (yourXRotation, yourYRotation, yourZRotation);
}
Change the 3 values (yourX/Y/ZRotation) according to your needs.
This isn't what I needed, it's my fault I should of specified that I wanted it to be a smooth transition
Answer by Glarmo · Feb 01, 2015 at 04:33 PM
Well somehow I have managed it... http://answers.unity3d.com/questions/46845/face-forward-direction-of-movement.html That question helped a lot so if you are having similar problems look at that :)
Answer by Alex_May · Feb 01, 2015 at 03:41 PM
Instead of setting the rotation directly, you could lerp towards it by some factor, e.g. 0.5.
transform.localEulerAngles = Vector3.Lerp(transform.localEulerAngles, targetRotation, 0.5f);