在更新功能之外移动带有动画的游戏对象
Moving a gameObject with Animation outside update function
我检查了如何在 Update()
函数中移动带动画的 gameObject
以便您可以使用 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()
{
}
}
实现此目标的更好方法是什么?
您可以使用 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;
}
我检查了如何在 Update()
函数中移动带动画的 gameObject
以便您可以使用 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()
{
}
}
实现此目标的更好方法是什么?
您可以使用 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;
}