#region 生成随机点
float minX = -800f;
float maxX = 800f;
float minY = -400f;
float maxY = 400f;
// 计算相邻点之间的间距
float distanceBetweenPoints = 500f;
// 生成指定数量的点
for (int i = 0; i < 12; i++)
{
// 随机生成点的位置
float randomX = UnityEngine.Random.Range(minX, maxX);
float randomY = UnityEngine.Random.Range(minY, maxY);
Vector2 newPoint = new Vector2(randomX, randomY);
if (i == 0)
{
mPosTf3.localPosition = newPoint;
mPos.Add(newPoint);
}
// 移动生成的点,确保相邻点之间的间距
if (i > 0)
{
// 随机生成点的位置
Vector2 randomPosition = new Vector3(UnityEngine.Random.Range(minX, maxX), UnityEngine.Random.Range(minY, maxY));
检查点的位置是否超出范围,如果是则重新随机位置
//while (IsPositionOutOfRange(randomPosition, mPos))
//{
// randomPosition = new Vector3(UnityEngine.Random.Range(minX, maxX), UnityEngine.Random.Range(minY, maxY), 0f);
//}
Vector2 previousPointPosition = mPos[i - 1];
Vector2 newPosition = previousPointPosition + (randomPosition - previousPointPosition).normalized * distanceBetweenPoints;
// 检查新位置是否超出范围,如果是则重新随机位置
while (IsPositionOutOfRange(newPosition))
{
randomPosition = new Vector2(UnityEngine.Random.Range(minX, maxX), UnityEngine.Random.Range(minY, maxY));
newPosition = previousPointPosition + (randomPosition - previousPointPosition).normalized * distanceBetweenPoints;
}
//Vector3 newPosition;
//do
//{
// // 随机生成点的位置
// newPosition = new Vector2(UnityEngine.Random.Range(minX, maxX), UnityEngine.Random.Range(minY, maxY));
//} while (Vector3.Distance(newPosition, mPos[i - 1]) < 500f&& Vector3.Distance(newPosition, mPos[i - 1])>300f); // 检查点与上一个点的距离是否小于500像素
mPos.Add(newPosition);
}
}
for (int i = 0; i < mPos.Count; i++)
{
Debug.Log($"mPos==={mPos[i]}");
}
#endregion
bool IsPositionOutOfRange(Vector2 position)
{
// 检查点的位置是否超出范围
float minX = -800f;
float maxX = 800f;
float minY = -400f;
float maxY = 400f;
if (position.x < minX || position.x > maxX || position.y < minY || position.y > maxY)
{
return true;
}
return false;
}