- Home /
How can I slowly rotate a sprite to face its movement direction?
I'm just starting out with all of this & this is a super basic question, but I haven't been able to find a solution that works anywhere.
I have a 2d sprite which moves around using the in-built physics system & I need it to face the direction it's moving, but I need it to rotate around slowly not just turn instantly.
Here's the script as it stands in case that helps:
public float movespeed;
private Rigidbody2D rb2d;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(moveHorizontal, moveVertical);
rb2d.AddForce(movement * movespeed);
}
Thanks in advance for the help
Answer by Brijs · Jun 16, 2016 at 11:02 AM
Try this :
IEnumerator Rotator()
{
Quaternion targetRotation = Quaternion.LookRotation(movementDirection);
Quaternion currentRotation = transform.rotation;
for (float i = 0; i < 1.0f; i += Time.deltaTime / timeToRotate)
{
transform.rotation = Quaternion.Lerp(currentRotation,targetRotation,i);
yield return null;
}
}
Here timeToRotate is total time in which you want to rotate sprite to movement direction
I'm sure I'm just making some simple mistake, but it isn't working. No errors or anything the sprite just acts exactly like it did before & doesn't rotate. Here's the script now:
public float movespeed;
public int rotatespeed;
private Rigidbody2D rb2d;
private Vector2 movement;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
//XY $$anonymous$$ovement
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(moveHorizontal, moveVertical);
rb2d.AddForce(movement * movespeed);
}
IEnumerator Rotator ()
{
Quaternion targetRotation = Quaternion.LookRotation(movement);
Quaternion currentRotation = transform.rotation;
for (float i = 0; i < 1.0f; i += Time.deltaTime / rotatespeed)
{
transform.rotation = Quaternion.Lerp(currentRotation, targetRotation, i);
yield return null;
}
}
You should start coroutine. This code works for 3d object. For 2D sprite Refer this How rotate only z axis of Gameobject (2D)