void UpdateBalls() { // 1. 先移除临时队列中的所有元素 deadBallList.Clear(); deadFoodList.Clear(); // 2. 刷新每个球 for (int i = 0; i < balls.Count; i++) { Ball ball = balls[i]; // 如果球已经死亡,则不再对其判断 if (!ball.isAlive) { continue; } for (int j = i + 1; j < balls.Count; j++) { Ball otherBall = balls[j]; // 如果球已经死亡,则不再对其判断 if (!otherBall.isAlive) { continue; } float radiusCompare = ball.radius - otherBall.radius; // 如果两个球大小相等,则不做判断 if (System.Math.Abs(radiusCompare) < BallData.RadiusTolerance) { continue; } Ball bigBall = (radiusCompare > 0) ? ball : otherBall; Ball smallBall = (bigBall == ball) ? otherBall : ball; float distance = Vector3.Distance(ball.position, otherBall.position); // 当小球的球心进入大球时,则将小球吃掉 if (distance < bigBall.radius) { bigBall.Eat(smallBall); smallBall.BeEaten(); deadBallList.Add(smallBall); // 先将被吃掉的球加入临时队列 } } for (int k = 0; k < foods.Count; k++) { Food food = foods[k]; if (!food.isAlive) { continue; } float distance = Vector3.Distance(ball.position, food.position); if (distance < ball.radius) { ball.Eat(food); food.BeEaten(); deadFoodList.Add(food); // 先将被吃掉的食物加入临时队列 } } // 每次外循环最后,如果球还存活,则刷新该球 if (ball.isAlive) { ball.Update(); } } // 3. 移除所有被吃掉的球和食物,并将该对象置空 for (int i = 0; i < deadBallList.Count; i++) { balls.Remove(deadBallList[i]); deadBallList[i] = null; } for (int i = 0; i < deadFoodList.Count; i++) { foods.Remove(deadFoodList[i]); deadFoodList[i] = null; } }