Unityでテクスチャ画像をCubeで表現:Instantiate
Unityでテクスチャ画像のピクセルカラーを取得できる。
それを使って、テクスチャ画像のピクセルカラーをCubeに反映させて並べることで画像を表現する。
環境
Windows10
Unity 2018.2.2f1
スクリプト
// 並べるCube [SerializeField] private GameObject pixelCube; // 最後にまとめて動かすために、親オブジェクトを用意 [SerializeField] private GameObject output; void Start () { // テクスチャを取得 Texture2D texture = (Texture2D)GetComponent<Renderer>().material.mainTexture; // テクスチャのピクセルカラーを取得 Color[] texturePixels = texture.GetPixels(); // 出力先の親オブジェクトの位置 Vector3 outputPosition = output.transform.position; // 出力するcubeのスケール Planeに対するピクセルの比率に合わせる float cubeScale = this.transform.localScale.x * 10 / texture.width; // cubeの出力位置 Vector3 pixelPosition; // 出力したcubeオブジェクト GameObject pixel; for (int y = 0; y < texture.height; y++) { for (int x = 0; x < texture.width; x++) { // cubeの出力位置を決定 親オブジェクトの位置を基準にcubeのスケールずつずらす pixelPosition = new Vector3(outputPosition.x + x * cubeScale, outputPosition.y - y * cubeScale, outputPosition.z); // cubeの出力 pixel = Instantiate(pixelCube, pixelPosition, Quaternion.identity, output.transform); // 出力したcubeの色を、対応するテクスチャのピクセルカラーに変更 pixel.GetComponent<Renderer>().material.color = texturePixels[x + texture.width * y]; // 出力したcubeのスケールを変更 pixel.transform.localScale = Vector3.one * cubeScale; } } // 出力結果が上下逆になってるので反転 output.transform.Rotate(180f, 0f, 0f); }
Texture2D.GetPixels()でテクスチャ画像のピクセルカラーを配列で取得できる。今回用いる画像は128x128ピクセルなので、配列のサイズは16384になる。最終的に画像のピクセル分Cubeを並べる。
左が元画像で右がCubeを並べたもの。
次 :
Unityでテクスチャ画像をCubeで表現:DrawMeshInstancedIndirect + Compute Shader - メモの穴