Created
September 17, 2019 03:48
-
-
Save igaln/8e32eb9cdb16ab271ca7dfb998738e40 to your computer and use it in GitHub Desktop.
Unity C# Procedural Floor using Perlin Noise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class ProceduralFloor : MonoBehaviour | |
{ | |
//prefab to instantiate | |
public GameObject floorTile; | |
//dimensions of the floor, set frrom the inspects | |
public int floorWidth; | |
public int floorHeight; | |
//range of movements on x and y | |
public float heightScale = 1.0F; | |
public float xScale = 10.0F; | |
//array to store all tiless | |
//we can also retreive these from the scene using getComponentofChildren() | |
//Decrlaring your own array makes it more explicit | |
public GameObject[] tiles; | |
void Start() | |
{ | |
tiles = new GameObject[floorWidth * floorHeight]; | |
GameObject parentTile = new GameObject(); | |
for (int k = 0; k < floorWidth; k++) | |
{ | |
for (int z = 0; z < floorHeight; z++) | |
{ | |
GameObject newTile = Instantiate<GameObject>(floorTile); | |
float height = heightScale * Mathf.PerlinNoise(k * xScale * (Time.deltaTime), heightScale * z * (Time.deltaTime)); | |
newTile.transform.position = new Vector3(k, height, z); | |
newTile.name = "tile_" + (k * floorWidth) + z; | |
tiles[(k * floorWidth) + z] = newTile; | |
newTile.transform.parent = parentTile.transform; | |
} | |
} | |
} | |
void Update() | |
{ | |
for (int k = 0; k < floorWidth; k++) | |
{ | |
for (int z = 0; z < floorHeight; z++) | |
{ | |
GameObject existingTile = tiles[(k * floorWidth) + z]; | |
float height = heightScale * Mathf.PerlinNoise(k * xScale * (Time.time ) * 0.001f, heightScale * z * (Time.time) * 0.001f); | |
existingTile.transform.position = new Vector3(k, height, z); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment