Reputation: 35
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;
}
}
}
Upvotes: 1
Views: 42
Reputation: 7356
That's because transform.Translate
translates the object in it's local space, not the world space.
When you do the following :
// The object will look at the opposite direction after this line
transform.rotation = Quaternion.LookRotation (Vector3.back);
speed *= -1;
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 :
IEnumerator Animate()
{
WaitForSeconds delay = new WaitForSeconds(2) ;
Quaterion backRotation = Quaternion.LookRotation (Vector3.back) ;
Quaterion forwardRotation = Quaternion.LookRotation (Vector3.forward) ;
while (true)
{
yield return delay;
transform.rotation = backRotation;
yield return delay;
transform.rotation = forwardRotation;
}
}
Upvotes: 2