- Home /
Rotate 2d object to facing direction
Hello Unity Community, I have some problems.
Im using accelerometer for moving my 2d sprite and the problem comes when i want to rotate my 2d sprite according to the device's accelerometer direction.
Now my code is rotating my character but not on the z axes, only on y and x
Do you know how can i do it to rotate only on z axes and to be facing to the direction
This is my code:
void Update ()
{
Vector3 move = Vector3.zero ;
move.x= Input.acceleration.x;
move.z = Input.acceleration.y;
transform.Translate(Vector3.right * (move.x * maxSpeed) * Time.deltaTime,Space.World);
transform.Translate(Vector3.up * (move.z * maxSpeed) * Time.deltaTime);
if (move != Vector3.zero)
{
transform.rotation = Quaternion.LookRotation(-move);
}
}
Any help will be appreciated !
Answer by robertbu · Mar 15, 2014 at 10:27 PM
I cannot verify your accelerometer calculations. If the vector is right, you can do this:
Vector3 dir = -move;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
This code assumes the front of the 2D object is on the right. If the front is up, then you need to subtract 90 from the angle before passing it to AngleAxis().
The rotation its working but now im facing with another problem. On the x axis it is moving very well but it dont move on the y ax , to move it on the y i have to face my device on the y +x , something in the middle
Also when im facing a negative direction its moving on the opposite direction
Done, i fixed it i change both direction to Space.World
Thank you again!! :3
sorry, im probably not smart enough. what did you actually change to make it work?
Thank you for this, 6 years in the future. This helped me tremendously.
yeah thx i already see this in black thorn udemy tutorial but forgot about it. Thx after 2 hrs of strugle. hello from begening 2021
im probably dumb, but what did you change from the code above to make it work?
Your answer
Follow this Question
Related Questions
Skips off block when landing 0 Answers
Slips off block when landing 0 Answers
How can I get the position of Input.touches in World Space? 1 Answer
compair data from vector3 1 Answer
Make Object smoothly follow player if out of near range 1 Answer