【问题标题】:Moving a gameObject with Animation outside update function在更新功能之外使用动画移动游戏对象
【发布时间】:2016-06-23 11:48:57
【问题描述】:

我检查了如何在Update() 函数内移动带有动画的gameObject,以便您可以使用Time.deltaTime,但我试图将gameObject 移动到此函数之外,我还想移动@987654325 @ 不断(在屏幕上随机移动)。我当前没有动画的代码是:

    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()
    {
    }
}

有什么更好的方法来实现这一点?

【问题讨论】:

    标签: android unity3d unityscript


    【解决方案1】:

    您可以使用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;
    }
    

    【讨论】:

    • 不能给 Vector3 添加浮点数,行 b = gameObject.transform.position.x + new Vector3(Random.Range(-0.1f, 0.1f), Random.Range(-0.1 f, 0.1f), 0);
    • 我假设你的意思是没有 position.x ?
    • 好的,所以我让你的代码工作了,我删除了 position.x 因为它给了我一个错误,切换了 Start() 函数中的命令顺序(如果你在 updatedestiny 之前调用 move 然后是向量a,b 是空的,每个游戏对象都将从 (0,0,0)) 开始 .. 谢谢 :)
    • 是的,您可以使用最终代码编辑我的帖子。不幸的是,我无法测试这段代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    相关资源
    最近更新 更多