画布层

Viewport(视窗)和 Canvas Item(画布项)

CanvasItem is the base for all 2D nodes, be it regular

2D nodes, such as Node2D, or Control <class_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.

通常情况下,我们并不希望游戏或应用程序中的 所有东西 都受到画布变换的约束。比如:

  • Parallax Backgrounds(视差背景) : 比场景其他部分移动得慢的背景.

  • UI: Think of a user interface (UI) or Heads-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.

  • Transitions(转场) : 我们应该希望用于转场的效果(淡入淡出之类的东西)也保持在固定的位置.

如何在单个场景树中解决这些问题?

CanvasLayer

答案是 CanvasLayer , 它是一个节点, 为所有子代和孙代添加一个单独的2D渲染层.Viewport的子节点默认在图层 "0 " 处绘制, 而CanvasLayer将在任何数字层处绘制. 数字较大的图层将绘制在数字较小的图层之上.CanvasLayers也有自己的变换, 不依赖于其他层的变换. 这使得当我们对游戏世界的观察发生变化时,UI可以固定在屏幕空间中.

比如说创建Parallax Background(视差背景). 这可以通过层为 "-1" 的CanvasLayer完成. 带有分数, 生命计数器和暂停按钮的屏幕也可以创建在编号为 "1" 的层中.

下面是它的图示:

../../_images/canvaslayers.png

CanvasLayer 独立于树顺序, 它们仅依赖于它们的层数, 因此可以只在需要时让它们实例化.

注解

CanvasLayer 不需要控制节点的绘制顺序. 确保节点被正确绘制在 "前面" 或 "后面" 的标准方法是操作场景面板中节点的顺序. 也许违反直觉, 场景面板中最上面的节点绘制在视图端口中较低的节点 后面 . 二维节点也有控制其绘图顺序的属性(参考 Node2D.z_index ).