Character not changing direction

2019-08-01 06:27发布

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;
    }
}
}

标签: unity3d
1条回答
姐就是有狂的资本
2楼-- · 2019-08-01 07:08

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 :

  1. Walk forward
  2. Rotate 180° and walk backward

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;
    }
}
查看更多
登录 后发表回答