Reputation: 1
I wrote a method that mirrors the player using their transform.localScale
:
void Flip()
{
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
Then I wrote some code in the update that rotates sprite to movement direction:
if (facingRight)
{
float angle = Mathf.Atan2(movement.y, movement.x) * Mathf.Rad2Deg;
float angleClamp = Mathf.Clamp(angle , -30.0f, 30.0f);
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, 0, angleClamp), rotateSpeed * Time.deltaTime);
}
else
{
Quaternion.Euler(0, 0, 0);
float angle = Mathf.Atan2(movement.y * -1, movement.x) * Mathf.Rad2Deg;
float angleClamp = Mathf.Clamp(angle, -30.0f, 30.0f);
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, 0, angleClamp), rotateSpeed * Time.deltaTime);
}
The movement
vector is the current player's inputs, using GetAxis()
:
float moveX = Input.GetAxis("Horizontal");
float moveY = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(moveX, moveY);
When facingRight == true
, the angle is correct; (when I move straight 0 degrees, all the way up and all the way down it's 90 and -90, and diagonally about 45 and -45)
But when facingRight == false
, the angle is wrong (when I move straight -180 degrees, all the way up and all the way down it's 90 and -90, and diagonally about 135 and -135)
How can I get the same values as in angle when turning to the right, but at the same time have them be the opposite? (in this code I make them opposite by multiplying movement.y
by -1)
Upvotes: 0
Views: 61
Reputation: 81
If you want the angle when facing left to be -1 multiplied by the angle when facing right, then calculate the angle as if it was facing right then multiply it by -1.
float angle = Mathf.Atan2(movement.y, movement.x) * Mathf.Rad2Deg;
float angleClamp = Mathf.Clamp(angle, -30.0f, 30.0f);
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, 0, angleClamp), rotateSpeed * Time.deltaTime);
if (!facingRight)
{
transform.rotation.eulerAngles = transform.eulerAngles * -1;
}
Upvotes: 0