//Use the logic I have made :
//The code can be more improve, but Its results are good.
private bool facingLeft = false;
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(horizontalInput, verticalInput);
movement = movement.normalized;
// Flip the character sprite based on movement direction
float angle = Mathf.Atan2(verticalInput, horizontalInput) * Mathf.Rad2Deg;
// Flip the angle if the x-coordinate is negative
if (movement.x > 0f)
{
// Apply the rotation and location to the object
transform.localScale = new Vector3(1, 1, 1); // Facing right
facingLeft = false;
if (movement.y > 0f)
{
transform.rotation = Quaternion.Euler(0f, 0f, angle);
}
else if (movement.y < 0f)
{
transform.rotation = Quaternion.Euler(0f, 0f, angle);
}
}
else if (movement.x < 0f)
{
// Apply the rotation and location to the object
transform.localScale = new Vector3(-1, 1, 1); // Facing Left
facingLeft = true;
angle += 180f;
if (movement.y > 0f)
{
transform.rotation = Quaternion.Euler(0f, 0f, angle);
}
else if (movement.y < 0f)
{
transform.rotation = Quaternion.Euler(0f, 0f, angle);
}
}
else if (movement.y > 0f)
{
if (!facingLeft)
{
transform.rotation = Quaternion.Euler(0f, 0f, angle);
// Facing Left
}
else
{
angle += 180f;
transform.rotation = Quaternion.Euler(0f, 0f, angle);
}
}
else if (movement.y < 0f)
{
if (!facingLeft)
{
transform.rotation = Quaternion.Euler(0f, 0f, angle);
// Facing Left
}
else
{
angle += 180f;
transform.rotation = Quaternion.Euler(0f, 0f, angle);
}
}
else if (!facingLeft && movement.y == 0f)
{
// Apply the rotation to the object
transform.localScale = new Vector3(1, 1, 1); // Facing right
transform.rotation = Quaternion.Euler(0f, 0f, 0f);
}
else if (facingLeft && movement.y == 0f)
{
transform.localScale = new Vector3(-1, 1, 1); // Facing left
transform.rotation = Quaternion.Euler(0f, 0f, 0f);
}