2D sprite rotation problem
Hello, long story short, code makes a sprite move around and rotate 180degress(from left to right and vise versa). All this is happening in 2D, note that. My problem and respectively question is, when the skeleton (im using a skeleton model) starts moving right in the beginning it works perfectly for 1-2 turns lets say, but at some point, he goes left but the sprite looks right, as if he's doing a moon walk or w/e it's called. I have absolutely no idea why it behaves like that.
private Animator anim;
private Rigidbody2D myRigidbody;
public bool isWalking;
public float walkTime;
private float walkCounter;
public float waitTime;
private float waitCounter;
private int WalkDirection;
public float moveSpeed;
public bool goingRight;
public void Start() {
myRigidbody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
waitCounter = waitTime;
walkCounter = walkTime;
}
public void Update()
{
Debug.Log("Direction " + WalkDirection);
Debug.Log(goingRight);
if (isWalking)
{
walkCounter -= Time.deltaTime;
anim.SetFloat("Speed", 0.5f);
switch (WalkDirection)
{
case 1:
goingRight = true;
myRigidbody.velocity = new Vector2(moveSpeed, 0);
break;
case 2:
goingRight = false;
myRigidbody.velocity = new Vector2(-moveSpeed, 0);
break;
}
if (walkCounter < 0)
{
anim.SetFloat("Speed", 0f);
isWalking = false;
walkCounter = walkTime;
}
}
else
{
waitCounter -= Time.deltaTime;
myRigidbody.velocity = Vector2.zero;
if (waitCounter <= 0)
{
Rotation();
ChooseDirection();
}
}
}
public void ChooseDirection()
{
isWalking = true;
WalkDirection = Random.Range(1, 3);
}
public void Rotation()
{
if (goingRight)
{
transform.Rotate(0f, 0f, 0f);
}
else
{
transform.Rotate(0f, 180f, 0f);
}
}
}
Comment