I have written a script card to spawn coin item. However, it only spawns correctly if the map is square. I have a round map, but it seems to spawn the same as a square map, which really doesn't work, because it will cause the coins to spawn outside the map. Anyone with any ideas please help me
CodePudding user response:
[SerializeField] GameObject coinPrefab;
[SerializeField] int coinsToSpawnCount;
private void Start()
{
SpawnCoins();
}
public void SpawnCoins()
{
for (int i = 0; i < coinsToSpawnCount; i )
{
GameObject temp = Instantiate(coinPrefab, transform);
temp.transform.position = GetRandomPointInCollider(GetComponent<Collider>());
}
}
Vector3 GetRandomPointInCollider(Collider collider)
{
Vector3 point = new Vector3(
Random.Range(collider.bounds.min.x, collider.bounds.max.x),
Random.Range(collider.bounds.min.y, collider.bounds.max.y),
Random.Range(collider.bounds.min.z, collider.bounds.max.z)
);
if (point != collider.ClosestPoint(point))
{
point = GetRandomPointInCollider(collider);
}
point.y = 1f;
return point;
}
CodePudding user response:
This determines spawn point to be inside a cube limited by collider bounds:
Vector3 point = new Vector3(
Random.Range(collider.bounds.min.x, collider.bounds.max.x),
Random.Range(collider.bounds.min.y, collider.bounds.max.y),
Random.Range(collider.bounds.min.z, collider.bounds.max.z)
);
Just try spawning randomly inside a unit sphere with a given radius instead:
Vector3 point = Random.insideUnitSphere * radius;