【发布时间】:2016-04-30 20:39:57
【问题描述】:
我的游戏中有散布在地形上的动物生成器。这个想法是只有当玩家在产卵器范围内时才会产生动物,但如果在产卵器附近有太多动物则不会。这是我到目前为止所做的,但现在我有点卡住了。谁能给我一些关于以下事情的指导:
- 是否正确计算了生成几率?例如,设置两只动物的生成几率分别为 10% 和 90% 是否实际上会使动物 A 有 10% 的几率生成而动物 B 有 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!");
}
}
【问题讨论】:
-
你应该在codereview.stackexchange.com上发帖,这类问题不在此处讨论
-
谢谢!甚至不知道 codereview.stackexchange.com