BFMTerrainGenerator.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. return null;
  25. }
  26. terrainObject.transform.parent = transform;
  27. // Add a Terrain Collider
  28. terrainObject.GetComponent<TerrainCollider>().terrainData = terrainData;
  29. return terrainObject.GetComponent<Terrain>();
  30. }
  31. private float[,] GenerateHeights(int mapWidth, int mapHeight)
  32. {
  33. float[,] heights = new float[mapWidth, mapHeight];
  34. float seed = Random.Range(0, 10000);
  35. // adjust noise parameters based on terrain type
  36. float currentNoiseScale = noiseScale;
  37. float currentHilliness = hilliness;
  38. switch (terrainType)
  39. {
  40. case BFMTerrainType.Forest:
  41. currentHilliness *= 0.5f;
  42. break;
  43. case BFMTerrainType.Mountain:
  44. currentNoiseScale *= 0.5f; // more frequent peaks
  45. currentHilliness *= 2.0f;
  46. break;
  47. case BFMTerrainType.Plain:
  48. currentHilliness *= 0.1f;
  49. break;
  50. }
  51. for (int x = 0; x < mapWidth; x++)
  52. {
  53. for (int y = 0; y < mapHeight; y++)
  54. {
  55. float xCoord = (float)x / mapWidth * currentNoiseScale + seed;
  56. float yCoord = (float)y / mapHeight * currentNoiseScale + seed;
  57. // Generate height using Perlin noise
  58. heights[x, y] = Mathf.PerlinNoise(xCoord, yCoord) * currentHilliness;
  59. }
  60. }
  61. return heights;
  62. }
  63. public void SetTerrainType(BFMTerrainType type)
  64. {
  65. terrainType = type;
  66. // To see the changes, the terrain needs to be regenerated.
  67. }
  68. // Additional methods for generating specific terrain features can be added here
  69. }