Created
March 20, 2019 06:42
-
-
Save gemfile0/f861c6d91f377d2aee7f477504f0b48b to your computer and use it in GitHub Desktop.
Excerpt from Brackeys video tutorial.
This file contains hidden or 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 UnityEngine; | |
[RequireComponent(typeof(MeshFilter))] | |
public class PerlinNoise : MonoBehaviour | |
{ | |
[SerializeField] int width = 256; | |
[SerializeField] int height = 256; | |
[SerializeField] float scale = 20f; | |
[SerializeField] float offsetX = 100f; | |
[SerializeField] float offsetY = 100f; | |
Renderer meshRenderer; | |
#region Unity Method | |
void Start() | |
{ | |
offsetX = Random.Range(0f, 99999f); | |
offsetY = Random.Range(0f, 99999f); | |
meshRenderer = GetComponent<Renderer>(); | |
} | |
void Update() | |
{ | |
meshRenderer.material.mainTexture = GenerateTexture(); | |
} | |
#endregion | |
#region Custom Method | |
Texture2D GenerateTexture() | |
{ | |
Texture2D texture = new Texture2D(width, height); | |
for (int x = 0; x < width; x++) | |
{ | |
for (int y = 0; y < height; y++) | |
{ | |
texture.SetPixel(x, y, CalculateColor(x, y)); | |
} | |
} | |
texture.Apply(); | |
return texture; | |
} | |
Color CalculateColor(int x, int y) | |
{ | |
float xCoord = (float)x / width * scale + offsetX; | |
float yCoord = (float)y / height * scale + offsetY; | |
float sample = Mathf.PerlinNoise(xCoord, yCoord); | |
return new Color(sample, sample, sample); | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment