使用动画更新功能移动gameObject

时间:2016-06-23 11:48:57

标签: android unity3d unityscript

我查看了如何在gameObject函数中移动带有动画的Update(),以便您可以使用Time.deltaTime,但我正在尝试将gameObject移到此函数之外,并且我还想经常移动gameObject(随机在屏幕上旅行)。我目前没有动画的代码是:

    using UnityEngine;
using System.Collections;

public class ObjectMovement : MonoBehaviour
{
    float x1, x2;
    void Start()
    {
        InvokeRepeating("move", 0f, 1f);
    }
    void move()
    {
        x1 = gameObject.transform.position.x;
        gameObject.transform.position += new Vector3(Random.Range(-0.1f, 0.1f), Random.Range(-0.1f, 0.1f), 0);
        x2 = gameObject.transform.position.x;
        if (x2 < x1)
            gameObject.GetComponent<SpriteRenderer>().flipX = true;
        else
            gameObject.GetComponent<SpriteRenderer>().flipX = false;
    }
    void Update()
    {
    }
}

实现这一目标的更好方法是什么?

1 个答案:

答案 0 :(得分:2)

您可以使用Lerp来帮助您。

Vector3 a, b;
float deltaTime = 1f/30f;
float currentTime;

void Start()
{
    InvokeRepeating("UpdateDestiny", 0f, 1f);
    InvokeRepeating("Move", 0f, deltaTime);
}

void Move()
{
    currentTime += deltaTime;
    gameObject.transform.position = Vector3.Lerp(a, b, currentTime);
}

void UpdateDestiny()
{
    currentTime = 0.0f;
    float x1, x2;
    a = gameObject.transform.position;
    x1 = a.x;
    b = gameObject.transform.position + new Vector3(Random.Range(-0.1f, 0.1f), Random.Range(-0.1f, 0.1f), 0);
    x2 = b.x;
    if (x2 < x1)
        gameObject.GetComponent<SpriteRenderer>().flipX = true;
    else
        gameObject.GetComponent<SpriteRenderer>().flipX = false;
}