86 lines
2.7 KiB
C#
86 lines
2.7 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEditor;
|
|
using UnityEngine;
|
|
|
|
public class MapDot : MonoBehaviour
|
|
{
|
|
|
|
public GameObject DotPrefab;
|
|
public GameObject SuperDotPrefab;
|
|
|
|
public int SuperDotNum;//超级豆子的数量
|
|
|
|
public LayerMask ObstadeLayer;
|
|
|
|
public GameObject startPosGameObject;
|
|
public GameObject endPosGameObject;
|
|
public Vector2 startPos;
|
|
public Vector2 endPos;
|
|
|
|
|
|
|
|
private void Awake()
|
|
{
|
|
startPos = startPosGameObject.transform.position;
|
|
endPos = endPosGameObject.transform.position;
|
|
GeneratePellets();
|
|
}
|
|
|
|
void GeneratePellets()
|
|
{
|
|
/*int minX = Mathf.FloorToInt(Mathf.Min(startPos.x, endPos.x));
|
|
int maxX = Mathf.CeilToInt(Mathf.Max(startPos.x, endPos.x));
|
|
int minY = Mathf.FloorToInt(Mathf.Min(startPos.y, endPos.y));
|
|
int maxY = Mathf.CeilToInt(Mathf.Max(startPos.y, endPos.y));*/
|
|
float minX = Mathf.Min(startPos.x, endPos.x);
|
|
float maxX = Mathf.Max(startPos.x, endPos.x);
|
|
float minY = Mathf.Min(startPos.y, endPos.y);
|
|
float maxY = Mathf.Max(startPos.y, endPos.y);
|
|
|
|
List<Vector2> validPositions = new List<Vector2>();//存储可生成的位置
|
|
|
|
for (float x = minX; x <= maxX; x++)
|
|
{
|
|
// int ram = Random.Range(0, 101);//随机数
|
|
for (float y = minY; y <= maxY; y++)
|
|
{
|
|
Vector2 checkPos = new Vector2(x, y);
|
|
|
|
// 检测Wall层碰撞体
|
|
Collider2D hit = Physics2D.OverlapBox(checkPos, Vector2.one * 0.1f, 0, ObstadeLayer);
|
|
if (!hit)
|
|
{
|
|
validPositions.Add(checkPos);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 第二阶段:随机选择超级豆位置
|
|
List<Vector2> superDotPositions = new List<Vector2>();
|
|
int superDotCount = Mathf.Min(SuperDotNum, validPositions.Count);//不会超出范围
|
|
|
|
// 使用Fisher-Yates洗牌算法进行随机选择
|
|
for (int i = 0; i < superDotCount; i++)
|
|
{
|
|
int randomIndex = Random.Range(i, validPositions.Count);//随机
|
|
Vector2 temp = validPositions[i];
|
|
validPositions[i] = validPositions[randomIndex];
|
|
validPositions[randomIndex] = temp;
|
|
|
|
superDotPositions.Add(validPositions[i]);
|
|
}
|
|
|
|
// 第三阶段:实例化所有豆子
|
|
foreach (Vector2 pos in validPositions)
|
|
{
|
|
bool isSuperDot = superDotPositions.Contains(pos);//循环当前值是不是超级豆
|
|
GameObject prefab = isSuperDot ? SuperDotPrefab : DotPrefab;//三目
|
|
Instantiate(prefab, pos, Quaternion.identity, transform);
|
|
GameManager.instance.AddDotNum(1);
|
|
}
|
|
}
|
|
|
|
}
|
|
|