Skip to content

Instantly share code, notes, and snippets.

@gemfile0
Created March 20, 2019 06:42
Show Gist options
  • Save gemfile0/f861c6d91f377d2aee7f477504f0b48b to your computer and use it in GitHub Desktop.
Save gemfile0/f861c6d91f377d2aee7f477504f0b48b to your computer and use it in GitHub Desktop.
Excerpt from Brackeys video tutorial.
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