我正在运行一些协同程序,每隔几秒就会将对象从一个位置移动到另一个位置。在某个时刻,我想禁用他们的对手。如何确保每个游戏对象都已完成' lerping'在禁用它的对撞机之前到新位置,以防止在飞跃过程中禁用对撞机?以下是相关代码:
IEnumerator moveObjToRight (Transform fromPosition, Vector3 toPosition, float duration, int newIndex) {
while (freePositions.Contains(objPositions[newIndex])) {
freePositions.Add (objPositions [newIndex - 1]);
filledPositions.Remove (objPositions [newIndex - 1]);
float counter = 0;
Transform startTrans = fromPosition;
freePositions.Remove (objPositions [newIndex]);
filledPositions.Add (objPositions [newIndex]);
while (counter < duration) {
counter += Time.deltaTime;
fromPosition.position = Vector3.Lerp (startTrans.position, toPosition, counter / duration);
yield return null;
}
if (newIndex < objPositions.Count) {
newIndex++;
if ((newIndex == 9) || !freePositions.Contains (objPositions [newIndex])) {
isMovingLeft = true;
yield return new WaitForSeconds (2.0f);
if (freePositions.Contains (objPositions [newIndex - 2])) {
toPosition = new Vector3(objPositions[newIndex - 2], startTrans.position.y, startTrans.position.z );
yield return StartCoroutine(moveObjToLeft(startTrans, toPosition, 1.0f, newIndex - 2));
}
else if (!freePositions.Contains (objPositions [newIndex - 2])) {
yield return new WaitForSeconds (3.0f);
toPosition = new Vector3(objPositions[newIndex - 2], startTrans.position.y, startTrans.position.z );
yield return StartCoroutine(moveObjToLeft(startTrans, toPosition, 1.0f, newIndex - 2));
}
}
}
startTrans.position = toPosition;
toPosition = new Vector3 (objPositions [newIndex], startTrans.position.y, startTrans.position.z);
int waitTime = Random.Range (3, 5);
yield return new WaitForSeconds (waitTime);
}
}
答案 0 :(得分:0)
IEnumerator LerpWithCompletionAction(Action onCompletion){
while(Vector3.Distance(this.transform.position, this.target.position)<0.001f)
{
// Lerp
yield return null
}
if(onCompletion != null) { onCompletion(); }
}
检查使用距离,因为您无法真正依赖于检查浮动比较。您可以降低检查值或增加检查值是否过早发生,或者是否因为太小而不会发生。
然后你这样打电话:
void DisableColliders(){ // Disable your colliders }
void AnyMethod()
{
StartCoroutine(LerpWithCompletionAction(DisableColliders));
}