我有在我的游戏中散布在地形上的动物的产卵者。这个想法是只有当一个玩家在产卵者的范围内时动物才会产卵,但是如果在产卵者的近距离范围内有太多的动物则不会产生动物。这是我迄今为止所做的,但现在我有点卡住了。任何人都可以给我一些关于以下几点的指导:C#动物Spawner逻辑 - 需要建议
- 生成的几率是否正确计算?例如以10%和90%的产卵率创造两个动物实际上会使动物A有10%的机会产卵,animalB有90%的机会或者我的数学错误?
- 我的半径计算是否正确?
- 最重要的是:我可以改善它吗?
代码:
[System.Serializable]
public class SpawnableAnimal
{
public string AnimalName;
public float spawnWeight;
public float spawnPercentage;
}
public class AnimalSpawner : MonoBehaviour {
public float maxSpawnRadius = 1000.0f;
public float noSpawnRadius = 700.0f;
public GameObject spawnedAnimal;
public SpawnableAnimal[] spawnableAnimals;
void Start() {
System.Random rand = new System.Random();
int randInt = rand.Next(0, 100);
float startTime = randInt/100f;
float repeatTime = randInt/100f;
InvokeRepeating("ReadyToSpawn", startTime, (60.0f + repeatTime));
}
void ReadyToSpawn()
{
Debug.Log("Ready to spawn");
bool canSpawn = true;
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
GameObject[] animals = GameObject.FindGameObjectsWithTag("Animal");
for(int i = 0; i < players.Length; i++)
{
if (Vector3.Distance(this.transform.position, players[i].transform.position) > maxSpawnRadius)
canSpawn = false;
if (Vector3.Distance(this.transform.position, players[i].transform.position) < noSpawnRadius)
canSpawn = false;
}
if (players.Length < 1)
canSpawn = false;
if (spawnedAnimal != null)
canSpawn = false;
if (canSpawn)
SpawnAnimal();
}
void SpawnAnimal()
{
System.Random rand = new System.Random();
double x = rand.NextDouble();
var totalWeight = spawnableAnimals.Select(a => a.spawnWeight).Sum();
for(int i = 0; i < spawnableAnimals.Length; i++)
{
float spawnPercentage = spawnableAnimals[i].spawnWeight/totalWeight;
if(x < spawnPercentage)
{
InstantiateAnimal(i);
return;
}
x -= spawnPercentage;
}
}
void InstantiateAnimal(int animalToSpawn)
{
if (animalToSpawn != -1)
spawnedAnimal = GameObject.Find("AnimalManager").GetComponent<AnimalManager>().SpawnAnimal(spawnableAnimals[animalToSpawn].AnimalName, this.transform.position, this.transform.rotation);
else Debug.Log("No animal to spawn!");
}
}
你应该在http://codereview.stackexchange.com/上发帖,这些问题在这里脱离主题 – Stephen
谢谢!甚至不知道codereview.stackexchange.com –