All I am trying to do is when the enemy turns around its sprite will flip, the code below is what I have managed but right now it only flips after two changes in direction which is close but not what I need. Please help.
[HideInInspector]
public bool facingRight = true;
public float speed;
Rigidbody2D rbody;
public float timer;
Animator anim;
public float directionx;
// Use this for initialization
void Start()
{
rbody = GetComponent<Rigidbody2D>();
StartCoroutine(Move(timer));
}
IEnumerator Move(float timer)
{
while (0 < 1)
{
Vector2 targetVelocity = new Vector2(directionx, 0);
rbody.velocity = targetVelocity * speed;
yield return new WaitForSeconds(timer);
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
Vector2 targetVelocity1 = new Vector2(-directionx, 0);
rbody.velocity = targetVelocity1 * speed;
yield return new WaitForSeconds(timer);
}
}
}
The code is pretty self-explicative, you only need to set one variable to know the direction that the player starts to move ( m_FacingRight
in my case) and then decide when you want that the "flip" occurs calling flipFunction()
:
private bool m_FacingRight = true; // For determining which way the player is currently facing.
private void flipFunction()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.