Skip to content

Instantly share code, notes, and snippets.

@yadurajiv
Created March 27, 2019 18:34
Show Gist options
  • Save yadurajiv/e57c8856e139a417e0187c573bff0dbf to your computer and use it in GitHub Desktop.
Save yadurajiv/e57c8856e139a417e0187c573bff0dbf to your computer and use it in GitHub Desktop.
Animated Terrain in Unity using height maps, Perlin Noise and Terrains as seen here - https://www.youtube.com/watch?v=V2zzUbfcnQU
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TerrainScript : MonoBehaviour
{
Terrain terrain;
public int depth = 20;
public int width = 256;
public int height = 256;
public float scale = 8f;
public float offsetX;
public float offsetY;
public float terrainXSpeed = 1.42f;
private void Start() {
offsetX = Random.Range(0f, 9999f);
offsetY = Random.Range(0f, 9999f);
}
void Update()
{
terrain = GetComponent<Terrain>();
terrain.terrainData = GenerateTerrain(terrain.terrainData);
offsetX += Time.deltaTime * terrainXSpeed;
}
TerrainData GenerateTerrain(TerrainData terrainData) {
terrainData.heightmapResolution = width + 1;
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] = CalucalteHeight(x, y);
}
}
return heights;
}
float CalucalteHeight(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