Unity3D鸟来回飞来飞去

时间:2015-09-25 10:09:09

标签: unity3d

我正在尝试创建一条沿着x轴在屏幕上移动的鸟。

bird.transform.position = Vector3.Lerp (pos1, pos2, (Mathf.Abs(speed * Time.time) + 1.0f) / 2.0f);

在Update()中使用此鸟只飞行一次。我想要它飞到右边后,它应该等待2-3秒,然后用不同的精灵飞回来。 transform.translate不能像这样工作。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

你需要输入另一个LERP以换取另一个方向并且有一个变量,以便鸟类大致飞行:

bool goleft;

if(goleft)
{
     if(transform.position != pos2)
     {
          transform.position = Vector3.Lerp (pos1, pos2, (Mathf.Abs(speed * Time.time) + 1.0f) / 2.0f);
     }
     else
     {
           goleft = false;
           //change the direction the bird is facing here
     }
}
else
{
     if(transform.position != pos1)
     {
          transform.position = Vector3.Lerp (pos2, pos1, (Mathf.Abs(speed * Time.time) + 1.0f) / 2.0f);
     }
     else
     {
           goleft = true;
           //change the direction the bird is facing here
     }
}

希望有所帮助

答案 1 :(得分:0)

未经测试但我会从这里开始:

Vector3[] posts;
int current = 0;
float speed = 5.0f;
float threshold = Single.Epsilon;
float delay = 2.0f;

public void Update() {
    if(!waiting && posts.Length > 0)
    {
        if(!Mathf.Approximately((posts[current].position - transform.position).sqrMagnitude, threshold)
        {
            float step = speed * Time.deltaTime;
            transform.position = Vector3.MoveTowards(transform.position, posts[current].position, step);
        }
        else StartCoroutine("Next");
    }
}

IEnumerator Next() {
    waiting = true;
    yield return new WaitForSeconds(delay);
    current = (current + 1) % posts.Length;
    waiting = false;
}

这也可以让你拥有任意数量的帖子,所有的动作动态都可以在Next()处理,而如果你想让他从帖子0开始。 .. 1 ... 2 ... 3 ... 0 ... 1 ..或0 ... 1 ... 2 ... 3 ... 2 ... 1 ...

如果您想要后者,只需将current = (current + 1) % posts.Length;更改为Mathf.PingPong(current + 1, posts.Length);

即可

答案 2 :(得分:0)

我会有点像这样:

input

你想得到的是textarea正在降低鸟的冷却时间。您可以轻松更改float flipCooldown float defaultFlipCooldown = 2.0f; bool isGoingRight; Vector2 pos1; Vector2 pos2; void Start() { flipCooldown = defaultFlipCooldown; isGoingRight = true; pos1 = new Vector2(0, 0); pos2 = new Vector2(5, 0); // whatever floats your boat } void Update() { Vector2 initialPosition = null; Vector2 finalPosition = null; if (flipCooldown <= 0) { isGoingRight = !isGoingRight flipCooldown = defaultFlipCooldown; ChangeSprite(); } if (isGoingRight) { initialPos = pos1; finalPos = pos2; } else { initialPos = pos2; finalPos = pos1; } bird.transform.position = Vector3.Lerp (initialPos, finalPos, (Mathf.Abs(speed * Time.time) + 1.0f) / 2.0f); flipCooldown -= Time.deltaTime; } 变量中的冷却时间。当它以一种方式完成时,它只会翻转位置,Time.deltaTime函数将执行其余的工作。 defaultFlipCooldown功能只是Lerp更改。

如果您不想要修复位置,您可以计算它将飞多少,定义最终位置,只需更改ChangeSpriteGetComponent<SpriteRenderer>().sprite

同样重要的是要注意pos1只能与 Coroutines 一起使用,这是处理线程的概念,绝不会像pos2这样的方法。您可以在Unity手册中了解有关Coroutines的更多信息:http://docs.unity3d.com/Manual/Coroutines.html