Created
December 23, 2018 07:25
-
-
Save kankikuchi/70937261ac26ae974f1a06b7b4bddfcb to your computer and use it in GitHub Desktop.
パーリンノイズでテクスチャを生成するクラス【Unity】
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
// PerlinNoiseTextureExample.cs | |
// http://kan-kikuchi.hatenablog.com/entry/What_is_PerlinNoise | |
// | |
// Created by kan.kikuchi on 2018.12.15. | |
using UnityEngine; | |
/// <summary> | |
/// パーリンノイズでテクスチャを生成するクラス | |
/// </summary> | |
public class PerlinNoiseTextureExample : MonoBehaviour { | |
//画像のサイズ | |
[SerializeField] | |
private int _width = 256, _height = 256; | |
//パーリンノイズに渡すxとyの初期値 | |
[SerializeField] | |
private Vector2 _initialSmaple = Vector2.zero; | |
//ノイズの大きさの倍率 | |
[SerializeField] | |
private float _noizeScale = 10f; | |
//生成したノイズを反映するテクスチャとその画素値 | |
private Texture2D _texture = null; | |
private Color[] _pixels; | |
//================================================================================= | |
//初期化 | |
//================================================================================= | |
private void Start() { | |
//生成したノイズを反映するテクスチャを作成し、そのテクスチャに設定する画素値の配列を作成 | |
_texture = new Texture2D(_width, _height); | |
_pixels = new Color[_texture.width * _texture.height]; | |
//テクスチャからスプライト作成、レンダラーに設定 | |
GetComponent<SpriteRenderer>().sprite = Sprite.Create( | |
texture : _texture, | |
rect : new Rect(0, 0, _texture.width, _texture.height), | |
pivot : new Vector2(0.5f, 0.5f) | |
); | |
//ノイズを計算 | |
CalcNoise(); | |
} | |
//Inspectorで値が変更された時などに呼ばれる | |
private void OnValidate() { | |
CalcNoise(); | |
} | |
//================================================================================= | |
//ノイズ計算 | |
//================================================================================= | |
//ノイズの計算 | |
private void CalcNoise() { | |
if(_texture == null){ | |
return; | |
} | |
//全画素に対して更新をかける | |
for (int x = 0; x < _texture.width; x++) { | |
for (int y = 0; y < _texture.height; y++) { | |
UpdatePixel(x, y); | |
} | |
} | |
//更新した画素をテクスチャに反映 | |
_texture.SetPixels(_pixels); | |
_texture.Apply(); | |
} | |
//画素値を更新する | |
private void UpdatePixel(int x, int y){ | |
//パーリンノイズに入力する値を決定 | |
float xSample = _initialSmaple.x + x / (float)_texture.width * _noizeScale; | |
float ySample = _initialSmaple.y + y / (float)_texture.height * _noizeScale; | |
//パーリンノイズで色を決定(0 ~ 1) | |
float color = Mathf.PerlinNoise(xSample, ySample); | |
//色を画素に設定 | |
_pixels[y * _texture.width + x] = new Color(color, color, color); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment