TerrainObjectSpawner.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using UnityEngine;
  2. using System.Collections.Generic; // Added for List
  3. public class TerrainObjectSpawner : MonoBehaviour
  4. {
  5. public GameObject orbPrefab;
  6. public int orbCount = 20;
  7. public LayerMask terrainLayer;
  8. public float meshMaxHeight = 25f;
  9. public GameObject enemyPrefab;
  10. public int enemyCount = 5;
  11. public float minDistanceBetweenOrbs = 15f;
  12. public void SpawnOrbs()
  13. {
  14. Debug.Log("Spawner: Starting process...");
  15. if (orbPrefab == null) return;
  16. int spawned = 0;
  17. int attempts = 0;
  18. List<Vector3> spawnedPositions = new List<Vector3>();
  19. while (spawned < orbCount && attempts < 1000) // Increased attempts for better scattering
  20. {
  21. attempts++;
  22. float x = Random.Range(-100f, 100f);
  23. float z = Random.Range(-100f, 100f);
  24. Vector3 rayStart = new Vector3(x, 500f, z);
  25. if (Physics.Raycast(rayStart, Vector3.down, out RaycastHit hit, 1000f, terrainLayer))
  26. {
  27. // Check distance from previously spawned orbs
  28. bool isTooClose = false;
  29. foreach (Vector3 pos in spawnedPositions)
  30. {
  31. if (Vector3.Distance(hit.point, pos) < minDistanceBetweenOrbs)
  32. {
  33. isTooClose = true;
  34. break;
  35. }
  36. }
  37. if (!isTooClose)
  38. {
  39. Instantiate(orbPrefab, hit.point + Vector3.up * 1.5f, Quaternion.identity);
  40. spawnedPositions.Add(hit.point);
  41. spawned++;
  42. }
  43. }
  44. }
  45. Debug.Log("Spawner: Successfully spawned " + spawned + " scattered orbs!");
  46. }
  47. public void SpawnEnemies()
  48. {
  49. int spawned = 0;
  50. int attempts = 0;
  51. while (spawned < enemyCount && attempts < 500)
  52. {
  53. attempts++;
  54. float x = Random.Range(-100f, 100f);
  55. float z = Random.Range(-100f, 100f);
  56. Vector3 rayStart = new Vector3(x, 500f, z);
  57. if (Physics.Raycast(rayStart, Vector3.down, out RaycastHit hit, 1000f, terrainLayer))
  58. {
  59. if (hit.point.y > meshMaxHeight * 0.5f)
  60. {
  61. Instantiate(enemyPrefab, hit.point + Vector3.up * 2f, Quaternion.identity);
  62. spawned++;
  63. }
  64. }
  65. }
  66. }
  67. public void SpawnExtraEnemies(int amount)
  68. {
  69. int extraSpawned = 0;
  70. while (extraSpawned < amount)
  71. {
  72. float x = Random.Range(-100f, 100f);
  73. float z = Random.Range(-100f, 100f);
  74. Vector3 rayStart = new Vector3(x, 500f, z);
  75. if (Physics.Raycast(rayStart, Vector3.down, out RaycastHit hit, 1000f, terrainLayer))
  76. {
  77. // Spawn them on hills as usual
  78. if (hit.point.y > meshMaxHeight * 0.4f)
  79. {
  80. Instantiate(enemyPrefab, hit.point + Vector3.up * 2f, Quaternion.identity);
  81. extraSpawned++;
  82. }
  83. }
  84. }
  85. }
  86. }