Unity:如何在没有 StartCoroutine 的情况下使用 Vector3.Lerp() 使精灵移动
Unity: How to make a sprite move using Vector3.Lerp() without StartCoroutine
我想在不使用 StartCoroutine 的情况下使用 Vector3.Lerp() 移动精灵。
起点和目标点要在脚本中设置。
我将精灵拖放到 Unity 编辑器中并 运行 它。
但是,精灵不会移动。谢谢
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
public class MyScript1 : MonoBehaviour {
public Sprite sprite;
GameObject gameObject;
SpriteRenderer spriteRenderer;
Vector3 startPosition;
Vector3 targetPosition;
void Awake()
{
gameObject = new GameObject();
spriteRenderer = gameObject.AddComponent<SpriteRenderer>();
}
private void Start()
{
spriteRenderer.sprite = sprite;
startPosition = new Vector3(-300, 100, 0);
targetPosition = new Vector3(100, 100, 0);
}
void Update()
{
transform.position = Vector3.Lerp(startPosition, targetPosition , Time.deltaTime*2f);
}
}
实际上它确实移动了,但只是一点点,而且只有一次。
问题出在lerp方法本身:传递Time.deltaTime*2f作为第三个参数是错误的。
lerp 方法的第三个参数决定了 startPosition 和 targetPosition 之间的一个点,它应该在 0 和 1 之间。它 returns startPosition 如果传递 0,在你的情况下它 returns 一个点非常非常接近 startPosition,因为与范围 (0..1)
相比,您传递了一个非常小的数字
我建议你阅读 unity docs about this method
像这样的东西会起作用:
void Update()
{
t += Time.deltaTime*2f;
transform.position = Vector3.Lerp(startPosition, targetPosition , t);
}
我想在不使用 StartCoroutine 的情况下使用 Vector3.Lerp() 移动精灵。 起点和目标点要在脚本中设置。 我将精灵拖放到 Unity 编辑器中并 运行 它。 但是,精灵不会移动。谢谢
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
public class MyScript1 : MonoBehaviour {
public Sprite sprite;
GameObject gameObject;
SpriteRenderer spriteRenderer;
Vector3 startPosition;
Vector3 targetPosition;
void Awake()
{
gameObject = new GameObject();
spriteRenderer = gameObject.AddComponent<SpriteRenderer>();
}
private void Start()
{
spriteRenderer.sprite = sprite;
startPosition = new Vector3(-300, 100, 0);
targetPosition = new Vector3(100, 100, 0);
}
void Update()
{
transform.position = Vector3.Lerp(startPosition, targetPosition , Time.deltaTime*2f);
}
}
实际上它确实移动了,但只是一点点,而且只有一次。
问题出在lerp方法本身:传递Time.deltaTime*2f作为第三个参数是错误的。
lerp 方法的第三个参数决定了 startPosition 和 targetPosition 之间的一个点,它应该在 0 和 1 之间。它 returns startPosition 如果传递 0,在你的情况下它 returns 一个点非常非常接近 startPosition,因为与范围 (0..1)
相比,您传递了一个非常小的数字我建议你阅读 unity docs about this method
像这样的东西会起作用:
void Update()
{
t += Time.deltaTime*2f;
transform.position = Vector3.Lerp(startPosition, targetPosition , t);
}