Canvas 圖層

Viewport 與 Canvas 項目

CanvasItem is the base for all 2D nodes, be it regular 2D nodes, such as Node2D, or Control. Both inherit from CanvasItem. You can arrange canvas items in trees. Each item will inherit its parent's transform: when the parent moves, its children move too.

CanvasItem nodes, and nodes inheriting from them, are direct or indirect children of a Viewport, that display them.

A Viewport has the property Viewport.canvas_transform, allows to apply a custom Transform2D transform to the CanvasItem hierarchy it contains. Nodes such as Camera2D work by changing that transform.

To achieve effects like scrolling, manipulating the canvas transform property is more efficient than moving the root canvas item and the entire scene with it.

Usually though, we don't want everything in the game or app to be subject to the canvas transform. For example:

  • 視察背景 (Parallax Background): 比畫面中其他部分動得慢的背景。

  • UI: Think of a user interface (UI) or head-up display (HUD) superimposed on our view of the game world. We want a life counter, score display and other elements to retain their screen positions even when our view of the game world changes.

  • 轉場: 在轉場 (淡入淡出、混合等) 使用的視覺效果上,我們會希望這些效果保留在畫面上固定的位置。

要如何在單一場景樹中解決這些問題?

CanvasLayer

這個問題的答案就是 CanvasLayer 。CanvasLayer 是一個可以為其所有子節點與次級子節點加上額外的 2D 算繪圖層的節點。Viewport 子節點預設會在第「0」層上進行繪製,而 CanvasLayer 則會在其他數字的圖層上繪製。較大數字的圖層會被繪製在較小數字的圖層之上。CanvasLayer 自己也有獨立的變換,並不收到其他圖層的變換影響。這樣一來,便可以讓 UI 繪製在畫面上固定的地方,觀看遊戲世界的更改便不受影響。

CanvasLayer 的其中一個例子就是建立視差背景。可以通過將背景放在 CanvasLayer「-1」上來實現。分數、生命計數器與暫停按鈕的畫面可以建立在第「1」層上。

下圖顯示了圖層的樣子:

../../_images/canvaslayers.png

CanvasLayer 與樹狀順序彼此獨立,其順序只會依據圖層數字來決定,因此可以依據需求來進行實體化。

備註

若要控制節點的繪製順序,也不一定要使用 CanvasLayer。要確保節點被繪製另一個節點的「前方」還是「後方」的標準方法是在場景面板中調整節點的順序。也許不太直覺,但在場景面板最上面的節點會在 Viewport 中會被繪製在下方節點的 後面 。2D 節點也有能控制繪製順序的屬性 (請參考 Node2D.z_index)。