2016-06-23 101 views
1

我檢查瞭如何使用動畫移動gameObjectUpdate()函數內,因此您可以使用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() 
    { 
    } 
} 

什麼是更好的實現方法?

回答

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

不能浮子添加的Vector3,線b = gameObject.transform.position.x +新的Vector3(Random.Range(-0.1f,0.1F),Random.Range(-0.1f, 0.1f),0); – DAVIDBALAS1

+1

我假設你的意思沒有position.x? – DAVIDBALAS1

+1

好吧,讓我的代碼工作,我刪除了position.x,因爲它給了我一個錯誤,切換了Start()函數內的命令順序(如果你在updatedestiny之前調用move,那麼矢量a,b都是空的,每個gameobject將從(0,0,0)開始)..謝謝:) – DAVIDBALAS1