我有在我的遊戲中散佈在地形上的動物的產卵者。這個想法是隻有當一個玩家在產卵者的範圍內時動物纔會產卵,但是如果在產卵者的近距離範圍內有太多的動物則不會產生動物。這是我迄今爲止所做的,但現在我有點卡住了。任何人都可以給我一些關於以下幾點的指導: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 –