LoginSignup
81
77

More than 5 years have passed since last update.

2Dの線を描画する【Unity】

Posted at

いくつか方法があったので、まとめます。

LineRenderer

空のGameObject → add component → Line Renderer を選択します。
マテリアルを設定すれば色などを設定できるようになります。

Line.cs
void Start () {
    LineRenderer renderer = gameObject.GetComponent<LineRenderer>();
    // 線の幅
    renderer.SetWidth(0.1f, 0.1f);
    // 頂点の数
    renderer.SetVertexCount(2);
    // 頂点を設定
    renderer.SetPosition(0, Vector3.zero);
    renderer.SetPosition(1, new Vector3(1f, 1f, 0f));
}

スクリーンショット 2015-07-20 14.19.27.png

GL.LINES

openGLの機能を直接つかって描く方法です。
空のGameObjectに以下のスクリプトを適応します。
lineMaterialには任意のマテリアルをUnity側で設定します。
この方法では線の幅を指定することができないようなので、GL.QUADSでポリゴンを作る必要があります。

GLLine.cs
public Material    lineMaterial;
void OnRenderObject () {
    lineMaterial (0);
    GL.PushMatrix ();
    GL.MultMatrix (transform.localToWorldMatrix);
    GL.Begin (GL.LINES);
    GL.Vertex3 (0f, 0f, 0f);
    GL.Vertex3 (1f, 1f, 0f);
    GL.End ();
    GL.PopMatrix ();
}

スクリーンショット 2015-07-20 14.34.30.png

Texture2D

これはテクスチャに直接ピクセルを書き込んでいく方法です。
空のGameObject → add component → GUI Texture を選択します。

TextureLine.cs
void Start () {
    // Texture2Dの作成.
    int width  = 256;
    int height = 256;
    Texture2D texture = new Texture2D(width, height);
    GUITexture tex = GetComponent<GUITexture>();
    tex.texture = texture;
    // テクスチャを真ん中に持ってきます
    Rect rect = new Rect();
    rect.Set(0f, 0f, Screen.width, Screen.height);
    tex.pixelInset = rect;

    // テクスチャ描画クラスの作成.
    DrawTexture2D drawTex2D = new DrawTexture2D();
    // テクスチャへ描画開始.
    drawTex2D.Begin(texture);   
    drawTex2D.Clear (new Color(0.0f, 0.0f, 0.0f));
    // 線の描画
    drawTex2D.DrawLine(0, 0, 128, 128, new Color(1f, 0f, 0f));
    // テクスチャへ描画終了.
    drawTex2D.End();
}

スクリーンショット 2015-07-20 14.57.13.png

81
77
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
81
77