- Home /
Rotating a 2D sprite
I want to rotate a 2D sprite based in its velocity, and currently I am using the following code:
void FixedUpdate ()
{
rigidbody2D.rotation = -rigidbody2D.velocity.x * 5;
}
The problem with this is as soon as I leave the direction key, it does not return to original state and stays at the same angle. Can any suggest any changes in the code to do the same?
Answer by PatrikL · Jul 07, 2015 at 12:13 PM
It sounds as if you want it to rotate only when your character is moving. In that case you could multiply your value by the input direction.
void FixedUpdate ()
{
rigidbody2D.rotation = -rigidbody2D.velocity.x * 5 * Input.GetAxis("Horizontal");
}
It might be the case where the input value changes to rapidly, and you want it to look smoother. Then you could ease the value using the Lerp function.
void FixedUpdate ()
{
rigidbody2D.rotation = Mathf.Lerp(rigidbody2D.rotation, -rigidbody2D.velocity.x * 5 * Input.GetAxis("Horizontal"), Time.deltaTime * 10f)
}
The value "10f" indicates how fast it should easy. Higher equals faster.
could you also any way to do it using touch controls. I am using swipe to control the character.