這是不工作的原因是因爲你沒有正確使用Lerp。線性插值(Lerp)的數學運算如下:
假設我們有一個點(0, 0)
和一個點(1, 1)
。爲了計算兩點之間的差距,我們提供的值爲0.0f
至1.0f
。這個t
表示兩點之間的比率(0.0f
是(0, 0)
和1.0f
是(1, 1)
)。例如,值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
。給我們答案的公式是c = a + (0.5f * (b - a))
。這來自對線性代數的基本理解,其中從彼此中減去兩個點導致向量,並且將向量添加到點給出另一點。
好吧,現在就讓這段代碼按照你想要的方式工作。你的腳本可能看起來像這樣:
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
}
}
希望這有助於!
我可以想象你需要完成的'other'移動動畫,然後。嘗試爲此啓動協程,並確保在相同的碰撞情況下不再啓動它。 – SimpleVar