TC_RandomSpawner.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using UnityEngine;
  2. using System.Collections;
  3. namespace TerrainComposer2
  4. {
  5. public class TC_RandomSpawner : MonoBehaviour
  6. {
  7. public GameObject spawnObject;
  8. public float posOffsetY = 1;
  9. public Vector2 posRangeX = new Vector2(-1000, 1000);
  10. public Vector2 posRangeZ = new Vector2(-1000, 1000);
  11. public Vector2 rotRangeY = new Vector2(-180, 180);
  12. public bool spawnOnStart;
  13. // Use this for initialization
  14. void Start()
  15. {
  16. if (spawnOnStart) Spawn();
  17. }
  18. public GameObject Spawn()
  19. {
  20. if (spawnObject == null) return null;
  21. Vector3 pos = transform.position;
  22. pos.x += Random.Range(posRangeX.x, posRangeX.y) * transform.localScale.x;
  23. pos.z += Random.Range(posRangeZ.x, posRangeZ.y) * transform.localScale.z;
  24. pos.y = SampleTerrainHeight(pos) + posOffsetY;
  25. Vector3 rot = new Vector3(0, Random.Range(rotRangeY.x, rotRangeY.y), 0);
  26. GameObject go = (GameObject)Instantiate(spawnObject, pos, Quaternion.Euler(rot));
  27. return go;
  28. }
  29. void OnDrawGizmosSelected()
  30. {
  31. Gizmos.DrawWireCube(transform.position, new Vector3((posRangeX.y - posRangeX.x) * transform.localScale.x * 2, 100, (posRangeZ.y - posRangeZ.x)) * transform.localScale.z * 2);
  32. }
  33. float SampleTerrainHeight(Vector3 pos)
  34. {
  35. TC_TerrainArea terrainArea = TC_Generate.instance.area2D.terrainAreas[0];
  36. for (int i = 0; i < terrainArea.terrains.Count; i++)
  37. {
  38. TCUnityTerrain tcTerrain = terrainArea.terrains[i];
  39. if (tcTerrain.terrain == null) continue;
  40. if (tcTerrain.terrain.terrainData == null) continue;
  41. Vector3 posTerrain = tcTerrain.terrain.transform.position;
  42. Vector3 sizeTerrain = tcTerrain.terrain.terrainData.size;
  43. Rect rect = new Rect(posTerrain.x, posTerrain.z, sizeTerrain.x, sizeTerrain.z);
  44. if (rect.Contains(pos))
  45. {
  46. return tcTerrain.terrain.SampleHeight(pos);
  47. }
  48. }
  49. return -1;
  50. }
  51. }
  52. }