我有一个立方体游戏对象与二维对撞机,当有人击中相机时应该上升10个单位,但平稳,相机去正确的位置,但没有阻尼。
public Transform target;
public float damping = 0.1f;
void OnTriggerEnter2D(Collider2D other)
{
Vector3 newPoint = Vector3.Lerp(target.transform.position,
target.transform.position + Vector3.up * 10.0f,
damping);
target.transform.position = newPoint;
}
最佳答案
这不起作用的原因是您没有正确使用LERP。这就是线性插值(LERP)的数学原理:
假设我们有一个点(0, 0)
和一个点(1, 1)
。为了计算点与点之间的距离,我们提供了一个从t
到0.0f
的1.0f
值。这表示两点之间的比率(t
表示0.0f
和(0, 0)
表示1.0f
)。例如,(1, 1)
的t
值将导致点0.5f
。
现在用一个不那么简单的例子对此进行扩展,考虑两点:(0.5f, 0.5f)
和var a = Vector2(1.0f, -1.0f)
。var b = Vector2(0.0f, 1.0f)
的结果是Lerp(a, b, 0.5f)
,因为这是中点。让我们调用答案Vector2(0.5f, 0.0f)
。给我们答案的方程式是c
。这来自于对线性代数的基本理解,在线性代数中,两个点从一个向量的结果中相减,然后在一个点上加一个向量得到另一个点。
好的,现在开始让这段代码按照你想要的方式工作。你的剧本可能是这样的:
float moveTime = 10.0f; // In seconds
float moveTimer = 0.0f; // Used for keeping track of time
bool moving = false; // Flag letting us know if we're moving
float heightChange = 10.0f; // This is the delta
// These will be assigned when a collision occurs
Vector3 target; // our target position
Vector3 startPos; // our starting position
void OnTriggerEnter2D(Collider2D other)
{
if (!moving)
{
// We set the target to be ten units above our current position
target = transform.position + Vector3.up * heightChange;
// And save our start position (because our actual position will be changing)
startPos = transform.position;
// Set the flag so that the movement starts
moving = true;
}
}
void Update()
{
// If we're currently moving and the movement hasn't finished
if (moving && moveTimer < moveTime)
{
// Accumulate the frame time, making the timer tick up
moveTimer += Time.deltaTime;
// calculate our ratio ("t")
float t = moveTimer / moveTime;
transform.position = Vector3.Lerp(startPos, target, t);
}
else
{
// We either haven't started moving, or have finished moving
}
}
希望这有帮助!