I've got a character that changes its facing (right or left) every two seconds. After that two seconds, the speed is multiplied by -1, so it changes its direction, but it just keeps going right (->)
Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour {
public int speed = 2;
void Start ()
{
StartCoroutine(Animate ());
}
void Update ()
{
float auto = Time.deltaTime * speed;
transform.Translate (auto, 0, 0);
}
IEnumerator Animate()
{
while (true) {
yield return new WaitForSeconds (2);
transform.rotation = Quaternion.LookRotation (Vector3.back);
speed *= -1;
yield return new WaitForSeconds (2);
transform.rotation = Quaternion.LookRotation (Vector3.forward);
speed *= -1;
}
}
}
That's because
transform.Translate
translates the object in it's local space, not the world space.When you do the following :
You flip your object and you ask to go in the opposite direction. Thus, the object will translate in the initial direction afterwards.
To fix your problem, I advise you to not change the value of the
speed
variable.Try to imagine yourself in the same situation :
In the end, you "continue" your path in the same direction
Here is the final method :