2016-06-23 123 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