首页 文章

Unity:如何在不使用StartCoroutine的情况下使用Vector3.Lerp()进行精灵移动

提问于
浏览
-3

我想使用没有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);
}
}

1 回答

  • 0

    实际上它确实移动但只是一点点而且只有一次 .

    问题在于lerp方法本身:传递Time.deltaTime * 2f作为第三个参数是错误的 .

    lerp方法的第三个参数决定startPosition和targetPosition之间的一个点,它应该在0和1之间 . 如果传递0,它返回startPosition,在你的情况下,它返回一个非常接近startPosition的点,因为你通过了一个非常小的数字比较到范围(0..1)

    我建议你看看unity docs about this method

    这样的东西会起作用:

    void Update()
    {        
        t += Time.deltaTime*2f;
        transform.position = Vector3.Lerp(startPosition, targetPosition , t);
    }
    

相关问题