一个简单的实例,演示了如何使用Vector3.Lerp来实现物体在两个位置之间平滑移动的效果:
using UnityEngine; public class ObjectMovement : MonoBehaviour { public Transform startPoint; public Transform endPoint; public float moveDuration = 2f; private float elapsedTime = 0f; private bool isMoving = false; private void Update() { if (Input.GetKeyDown(KeyCode.Space) && !isMoving) { StartMoving(); } if (isMoving) { MoveObject(); } } private void StartMoving() { elapsedTime = 0f; isMoving = true; } private void MoveObject() { elapsedTime += Time.deltaTime; if (elapsedTime >= moveDuration) { // 移动完成 transform.position = endPoint.position; isMoving = false; } else { // 在起始点和结束点之间平滑移动 float t = elapsedTime / moveDuration; transform.position = Vector3.Lerp(startPoint.position, endPoint.position, t); } } }
当按下space键的时候,正方形从开始点到结束点平滑移动,lerp函数不断生成中间经过的点