- Home /
Animator undoes sprite rotation
I'm modding the 2d platformer project to a top-down view and I'm trying to rotate the sprite to face the direction of the joystick/arrow keys. This works only when the keys are held down. It always goes back to facing right, unless I disable the animator
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
if (!(v == 0 && h == 0))
{
float angle = Mathf.Atan2 (v, h) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis (angle, Vector3.forward);
}
Once I release the keys the sprite will always change back to facing right, even if the sprite is still moving in another direction. For me it is desirable for the sprite to be looking in a different direction than movement (think ice or slippery surfaces) so rotating toward movement direction won't work. How can I lock in this rotation? Disabling the animator works, but then the movement becomes really choppy and laggy.
Answer by eightbitstev · Mar 21, 2014 at 05:21 AM
I imagine that the Animator is constantly setting the rotation of the character and you are merely overriding it here? I've never opened up the 2D platformer project, but I would try storing your calculated rotation to a cached variable and then set rotation to the cached variable every frame, only updating it when you receive input.
Quaternion rot;
void Update(){
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
if (!(v == 0 && h == 0))
{
float angle = Mathf.Atan2 (v, h) * Mathf.Rad2Deg;
rot = Quaternion.AngleAxis (angle, Vector3.forward);
}
transform.rotation = rot;
}