2Dカスタム描画

はじめに

Godotには、スプライト、ポリゴン、パーティクル、あらゆる種類のものを描画するノードがあります。ほとんどの場合、これで十分です。しかしそれがすべてではありません。その特定の 何か を描画するノードが存在しないため、恐怖、不安、怒りで泣く前に...簡単に任意の2Dノード(Control または Node2D ベース)を作成できることを知っておくとよいでしょう。そして、作成したノードでカスタムコマンドを描画します。それも 本当に 簡単に行えます。

Custom drawing in a 2D node is really useful. Here are some use cases:

  • Drawing shapes or logic that existing nodes can't do, such as an image with trails or a special animated polygon.

  • ノードと互換性のない視覚化、例えばテトリスボード等。 (テトリスの例では、カスタム描画関数を使用してブロックを描画します。)

  • Drawing a large number of simple objects. Custom drawing avoids the overhead of using a large number of nodes, possibly lowering memory usage and improving performance.

  • Making a custom UI control. There are plenty of controls available, but when you have unusual needs, you will likely need a custom control.

描画

ControlNode2D のような CanvasItem から派生したノードにスクリプトを追加します。次に _draw() 関数をオーバーライドします。

extends Node2D

func _draw():
    # Your draw commands here
    pass

描画のコマンドについては、 CanvasItem クラスリファレンスを参照してください。たくさんあります。

描画の更新

_draw() 関数は一度だけ呼び出され、その後は描画コマンドがキャッシュされて記憶されるため、それ以上の呼び出しは不要です。

If re-drawing is required because a state or something else changed, call CanvasItem.update() in that same node and a new _draw() call will happen.

次に、もう少し複雑な例を示します。テクスチャ変数を変更すると再描画されます:

extends Node2D

export (Texture) var texture setget _set_texture

func _set_texture(value):
    # If the texture variable is modified externally,
    # this callback is called.
    texture = value  # Texture was changed.
    update()  # Update the node's visual representation.

func _draw():
    draw_texture(texture, Vector2())

場合によっては、すべてのフレームを描画することが望ましい場合があります。このためには、次のように _process() コールバックから update() を呼び出すだけです:

extends Node2D

func _draw():
    # Your draw commands here
    pass

func _process(delta):
    update()

例:円弧の描画

次に、Godotエンジンのカスタム描画機能を使用して、Godotが機能を提供しないものを描画します。たとえば、Godotには円全体を描画する draw_circle() 関数が用意されています。しかし、円の一部を描くのはどうでしょうか?自分でこれを実行して描画をするには、関数をコーディングする必要があります。

Arc関数

円弧は、サポート円パラメーター、つまり中心位置と半径によって定義されます。円弧自体は、開始角度と停止角度によって定義されます。これらは、描画関数に提供する必要がある4つの引数です。また、色の値も提供するため、必要に応じて異なる色で弧を描くことができます。

Basically, drawing a shape on the screen requires it to be decomposed into a certain number of points linked from one to the next. As you can imagine, the more points your shape is made of, the smoother it will appear, but the heavier it will also be in terms of processing cost. In general, if your shape is huge (or in 3D, close to the camera), it will require more points to be drawn without it being angular-looking. On the contrary, if your shape is small (or in 3D, far from the camera), you may decrease its number of points to save processing costs; this is known as Level of Detail (LOD). In our example, we will simply use a fixed number of points, no matter the radius.

func draw_circle_arc(center, radius, angle_from, angle_to, color):
    var nb_points = 32
    var points_arc = PoolVector2Array()

    for i in range(nb_points + 1):
        var angle_point = deg2rad(angle_from + i * (angle_to-angle_from) / nb_points - 90)
        points_arc.push_back(center + Vector2(cos(angle_point), sin(angle_point)) * radius)

    for index_point in range(nb_points):
        draw_line(points_arc[index_point], points_arc[index_point + 1], color)

形状を分解する必要があるポイントの数を覚えていますか? nb_points 変数のこの数値を 32 の値に修正しました。次に、空の PoolVector2Array を初期化します。これは、単に Vector2 の配列です。

次のステップでは、円弧を構成する32個の点の実際の位置を計算します。これは最初のforループで行われ、位置を計算したいポイントの数に最後のポイントを含めるために1を加えて繰り返します。最初に、開始角度と終了角度の間の各点の角度を決定します。

各角度が90°減算される理由は、三角関数(コサインとサインなど)を使用して各角度から2D位置を計算するためです。ただし、簡単にするために、cos() および sin() は度ではなくラジアンを使用します。 0°(0ラジアン)の角度は3時から始まりますが、12時からカウントを開始します。したがって、12時からカウントを開始するために、各角度を90°ずつ減らします。

角度 angle (ラジアン単位)の円上にある点の実際の位置は、Vector2(cos(angle),sin(angle)) で与えられます。cos() および sin() は-1から1の間の値を返すため、点の位置は半径1の円上にあります。目標の半径にするには、単に点の位置に radius を乗算するだけです。次に、サポートサークルを center の位置に配置する必要があります。これは Vector2 の値に``center`` を加算することで実行されます。最後に、以前に定義した PoolVector2Array にポイントを挿入します。

次に、実際にポイントを描画する必要があります。ご想像のとおり、単純に32ポイントを描画するのではなく、それぞれの間にあるすべてのものを描画する必要があります。前の方法を使用してすべてのポイントを自分で計算し、それを1つずつ描画することもできます。しかし、これはあまりに複雑で非効率的であるため(明示的に必要な場合を除く)、各ポイントのペア間に単純に線を引きます。サポート円の半径が大きくない限り、1組のポイント間の各線の長さは、それらが個々の直線として見えてしまう長さになることはありません。もしもその場合は、ポイント数を増やすだけで済みます。

画面上に円弧を描画する

これで、画面上に物を描画する関数ができました。_draw() 関数内で呼び出します:

func _draw():
    var center = Vector2(200, 200)
    var radius = 80
    var angle_from = 75
    var angle_to = 195
    var color = Color(1.0, 0.0, 0.0)
    draw_circle_arc(center, radius, angle_from, angle_to, color)

結果:

../../_images/result_drawarc.png

Arc polygon関数

これをさらに一歩進めて、円弧で定義されたディスクのプレーン部分だけでなく、その形状を描画する関数を作成することもできます。この処理は、線の代わりに多角形を描くことを除いて、以前とまったく同じです:

func draw_circle_arc_poly(center, radius, angle_from, angle_to, color):
    var nb_points = 32
    var points_arc = PoolVector2Array()
    points_arc.push_back(center)
    var colors = PoolColorArray([color])

    for i in range(nb_points + 1):
        var angle_point = deg2rad(angle_from + i * (angle_to - angle_from) / nb_points - 90)
        points_arc.push_back(center + Vector2(cos(angle_point), sin(angle_point)) * radius)
    draw_polygon(points_arc, colors)
../../_images/result_drawarc_poly.png

動的カスタム描画

さて、私たちは今、画面上にカスタムのものを描画できるようになりました。ただし、動きません。そこで、この図形を中心で回してみましょう。これを行うための解決策は、単にangle_fromとangle_toの値を経時的に変更させることです。この例では、単純に50ずつインクリメントします。このインクリメント値は一定のままにする必要があります。そうしないと、それに応じて回転速度が変化します。

まず、スクリプトの先頭で、angle_from変数とangle_to変数の両方をグローバルにする必要があります。また、他のノードに保存し、get_node() を使用してアクセスすることもできます。

extends Node2D

var rotation_angle = 50
var angle_from = 75
var angle_to = 195

これらの値は_process(delta)関数で変更します。

ここではangle_fromとangle_to値をインクリメントします。ただし、0から360°の間に結果の値を wrap() することを忘れてはなりません。つまり、角度が361°の場合、実際には1°です。これらの値をラップしない場合、スクリプトは当面は正しく動作しますが、Godot が管理できる最大整数値 (2^31 - 1)に達するまで、角度の値は時間の経過と共に大きくなります。この現象を放置すると、Godotがクラッシュしたり、予期しない動作が発生する可能性があります。

最後に、自動的に _draw() を呼び出す update() 関数を呼び出すことを忘れてはなりません。これにより、フレームを更新するタイミングを制御できます。

func _process(delta):
    angle_from += rotation_angle
    angle_to += rotation_angle

    # We only wrap angles when both of them are bigger than 360.
    if angle_from > 360 and angle_to > 360:
        angle_from = wrapf(angle_from, 0, 360)
        angle_to = wrapf(angle_to, 0, 360)
    update()

また、これらの変数を利用するために _draw() 関数を変更することを忘れないでください:

func _draw():
   var center = Vector2(200, 200)
   var radius = 80
   var color = Color(1.0, 0.0, 0.0)

   draw_circle_arc( center, radius, angle_from, angle_to, color )

実行しましょう!動作はしますが、アークがものすごい速さで回転しています!何故でしょうか?

その理由は、GPUが実際にできるだけ速くフレームを表示しているからです。この速度で図面を「正規化」する必要があります。そのためには、_process() 関数の delta パラメーターを利用する必要があります。delta には、最後にレンダリングされた2つのフレーム間の経過時間が含まれます。通常は小さい(約0.0003秒ですが、これはハードウェアによって異なります)ため、delta を使用して描画を制御すると、プログラムがすべてのハードウェアで同じ速度で実行されます。

この場合、単に _process() 関数で rotation_angle 変数に delta を乗算するだけです。このように、2つの角度は、レンダリング速度に直接依存する非常に小さな値で増加します。

func _process(delta):
    angle_from += rotation_angle * delta
    angle_to += rotation_angle * delta

    # We only wrap angles when both of them are bigger than 360.
    if angle_from > 360 and angle_to > 360:
        angle_from = wrapf(angle_from, 0, 360)
        angle_to = wrapf(angle_to, 0, 360)
    update()

もう一度実行しましょう!今度は、回転が正常に表示されます!

Antialiased drawing

Godot offers method parameters in draw_line to enable antialiasing, but it doesn't work reliably in all situations (for instance, on mobile/web platforms, or when HDR is enabled). There is also no antialiased parameter available in draw_polygon.

As a workaround, install and use the Antialiased Line2D add-on (which also supports antialiased Polygon2D drawing). Note that this add-on relies on high-level nodes, rather than low-level _draw() functions.

ツール

Drawing your own nodes might also be desired while running them in the editor. This can be used as a preview or visualization of some feature or behavior. See エディタでコードを実行する for more information.