Skip to content

Instantly share code, notes, and snippets.

@yumayanagisawa
Created October 19, 2017 08:06
Show Gist options
  • Select an option

  • Save yumayanagisawa/a1d0905c279fb6f903c14d37259154a2 to your computer and use it in GitHub Desktop.

Select an option

Save yumayanagisawa/a1d0905c279fb6f903c14d37259154a2 to your computer and use it in GitHub Desktop.
Unity | Procedural Terrain
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TerrainGenerator : MonoBehaviour {
public int depth = 20;
public int width = 256;
public int height = 256;
public int scale = 20;
public float offsetX = 100f;
public float offsetY = 100f;
// Use this for initialization
void Start () {
offsetX = Random.Range(0f, 9999f);
offsetY = Random.Range(0f, 9999f);
}
// Update is called once per frame
void Update()
{
Terrain terrain = GetComponent<Terrain>();
terrain.terrainData = GenerateTerrain(terrain.terrainData);
offsetX += Time.deltaTime * 1.0f;
}
TerrainData GenerateTerrain(TerrainData terrainData)
{
terrainData.heightmapResolution = width;
terrainData.size = new Vector3(width, depth, height);
terrainData.SetHeights(0, 0, GenerateHeights());
return terrainData;
}
float[, ] GenerateHeights()
{
float[,] heights = new float[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
heights[x, y] = CalculateHeight(x, y);
}
}
return heights;
}
float CalculateHeight(int x, int y)
{
float xCoord = (float)x / width * scale + offsetX;
float yCoord = (float)y / height * scale + offsetY;
return Mathf.PerlinNoise(xCoord, yCoord);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment