PerlinNoise
unknown
csharp
3 years ago
1.6 kB
1
Indexable
Never
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PerlinNoise : MonoBehaviour { [SerializeField] int width = 256; [SerializeField] int height = 256; [SerializeField][Range(1f, 200f)] float scale = 20f; [SerializeField][Range(1f, 1000f)] float offsetX = 100f; [SerializeField][Range(1f, 1000f)] float offsetY = 100f; public bool autoUpdate; void Start() { CreateMap(); } public void CreateMap() { Renderer renderer = GetComponent<Renderer>(); renderer.material.mainTexture = GenerateTexture(); } Texture2D GenerateTexture() { Texture2D texture = new Texture2D(width, height); CreateNoise(texture); texture.Apply(); return texture; } void CreateNoise(Texture2D texture) { //Perlin Noise Map for (int x = 0; x < width; x++) { //Goes 256 times. for (int y = 0; y < height; y++) { //Going one x then 256 y's until all 256 x's are done. Color color = CalculateColor(x, y); texture.SetPixel(x, y, color); } } } Color CalculateColor(int x, int y) //Needs to go from 0 to 1 instead of 0 to 256 pixels. { 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); } }