初心者のUnity勉強① テクスチャに絵を描く
Unityって便利だなと言うことに気づいたので,学んだこととかつらつらと書いていこうと思う.ほぼ自分用です.
ちなみに「Unity2017入門 最新開発環境による簡単3D&2Dゲーム制作 」は読了済み.
Version: Unity2017.3.0p4
将来は知育用のラクガキ王国(ps2のソフト)みたいなことやりたいな.Hololensとか使って,現実空間で作ってそれが動く!戦う!みたいな.
とりあえず,その第一歩としておもちゃラボさんの記事をやってみる.
スクリプトの中身を読んで見る
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DrawingTexture : MonoBehaviour { Texture2D drawTexture; Color[] buffer; // Use this for initialization void Start () { Texture2D mainTexture = (Texture2D)GetComponent<Renderer> ().material.mainTexture; Color[] pixels = mainTexture.GetPixels (); // テクスチャのピクセルをバッファ用の配列にコピー buffer = new Color[pixels.Length]; pixels.CopyTo (buffer, 0); drawTexture = new Texture2D (mainTexture.width, mainTexture.height, TextureFormat.RGBA32, false); drawTexture.filterMode = FilterMode.Point; } public void Draw(Vector2 p) { for(int x = 0; x < 256; x++) { for(int y = 0; y < 256; y++) { // Rayのpositionとピクセルのベクトルの長さの差が5以内の距離ならば黒くする if ((p - new Vector2 (x, y)).magnitude < 5) { buffer.SetValue (Color.black, x + 256 * y); } } } } // Update is called once per frame void Update () { // マウスがドラッグされている部分を黒色で更新 if(Input.GetMouseButton (0)) { // Rayを飛ばしてヒットした所を検出 Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); RaycastHit hit; if(Physics.Raycast (ray, out hit, 100.0f)) { Draw (hit.textureCoord * 256); } drawTexture.SetPixels (buffer); drawTexture.Apply (); GetComponent<Renderer> ().material.mainTexture = drawTexture; } } }
流れとしてはこんな感じ
- テクスチャのピクセルをバッファにコピー
- マウスクリックしたポイントからレイを飛ばす
- 飛ばしたレイと衝突した平面がぶつかった場所を取得
- Draw関数にそのポジションを送る
- Draw関数でそのポジションとピクセルのベクトルとの大きさの差が5以内の時黒くする
こんなかんじで描画できた
もっときれいな絵を出したいけどunityシェーダとか勉強しないとだめっぽい?