首页 文章

Vector3.Lerp与Unity中的代码

提问于
浏览
2

我正在制作基本的2D太空射击游戏 . 我的动作很好,相机跟着玩家 . 我一直在摸索如何让摄像机稍微延迟,让玩家移动到摄像机移动以便在没有传送的情况下赶上它 . 有人告诉我使用Vector3.Lerp并尝试了stackoverflow答案中的一些内容,但似乎没有一个与我的代码设置方式一致 . 有什么建议? (myTarget链接到播放器)

public class cameraFollower : MonoBehaviour {
public Transform myTarget;


void Update () {
    if(myTarget != null){
        Vector3 targPos = myTarget.position;
        targPos.z = transform.position.z;
        transform.position = targPos;

        }

    }
}

2 回答

  • 2

    使用相机移动的想法是逐渐平稳地让相机进入目标位置 .

    相机越远,每帧的距离就越大,但相机越近,每帧的距离就越小,使相机更容易进入目标位置 .

    例如,尝试将 transform.position = targPos; 行替换为:

    float speed = 2.5f; // Set speed to whatever you'd like
    transform.position = Vector3.Lerp(transform.position, targPos, Time.deltaTime * speed);
    
  • 3

    如果你进行线性插值(Lerp),你可能会冒Time.deltaTime * speed> 1,在这种情况下相机会开始推断 . 也就是说,如果你的目标,它不会跟随它,而是会在前面 . 另一种方法是在线性插值中使用pow .

    float speed = 2.5f;
    float smooth = 1.0f - Mathf.Pow(0.5f, Time.deltaTime * speed);
    transform.position = Vector3.Lerp(transform.position, targetPos, smooth);
    

    Mathf.Pow(0.5,时间)意味着在1 /速度秒之后,将到达目标点的距离的一半 .

相关问题