BFMTerrainGenerator.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using Unity.VisualScripting;
  2. using Unity.VisualScripting.Antlr3.Runtime.Tree;
  3. using UnityEngine;
  4. public class BFMTerrainGenerator : MonoBehaviour
  5. {
  6. [Header("Terrain Settings")]
  7. public float terrainMaxHeight = 20f;
  8. public float hilliness = 1.0f;
  9. public float noiseScale = 20f;
  10. public BFMTerrainType terrainType;
  11. public Terrain GenerateTerrain(int width, int height)
  12. {
  13. TerrainData terrainData = new TerrainData();
  14. int heightmapResolution = width + 1;
  15. terrainData.heightmapResolution = heightmapResolution;
  16. terrainData.size = new Vector3(width, terrainMaxHeight, height);
  17. // Generate heightmap
  18. float[,] heights = GenerateHeights(heightmapResolution, heightmapResolution);
  19. terrainData.SetHeights(0, 0, heights);
  20. // Create terrain GameObject
  21. GameObject terrainObject = Terrain.CreateTerrainGameObject(terrainData);
  22. if (terrainObject == null)
  23. {
  24. Debug.LogError("Failed to create terrain object. Check if the terrain width and height are a power of two (e.g., 128, 256, 512).");
  25. return null;
  26. }
  27. terrainObject.transform.parent = transform;
  28. // Add a Terrain Collider
  29. terrainObject.GetComponent<TerrainCollider>().terrainData = terrainData;
  30. return terrainObject.GetComponent<Terrain>();
  31. }
  32. private float[,] GenerateHeights(int mapWidth, int mapHeight)
  33. {
  34. float[,] heights = new float[mapWidth, mapHeight];
  35. float seed = Random.Range(0, 10000);
  36. // adjust noise parameters based on terrain type
  37. float currentNoiseScale = noiseScale;
  38. float currentHilliness = hilliness;
  39. switch (terrainType)
  40. {
  41. case BFMTerrainType.Forest:
  42. currentHilliness *= 0.5f;
  43. break;
  44. case BFMTerrainType.Mountain:
  45. currentNoiseScale *= 0.5f; // more frequent peaks
  46. currentHilliness *= 2.0f;
  47. break;
  48. case BFMTerrainType.Plain:
  49. currentHilliness *= 0.1f;
  50. break;
  51. }
  52. for (int x = 0; x < mapWidth; x++)
  53. {
  54. for (int y = 0; y < mapHeight; y++)
  55. {
  56. float xCoord = (float)x / mapWidth * currentNoiseScale + seed;
  57. float yCoord = (float)y / mapHeight * currentNoiseScale + seed;
  58. // Generate height using Perlin noise
  59. heights[x, y] = Mathf.PerlinNoise(xCoord, yCoord) * currentHilliness;
  60. }
  61. }
  62. return heights;
  63. }
  64. public void SetTerrainType(BFMTerrainType type)
  65. {
  66. terrainType = type;
  67. // To see the changes, the terrain needs to be regenerated.
  68. }
  69. // Additional methods for generating specific terrain features can be added here
  70. }