在上个教程中我们以官方提供的案例《视口 之 3d in 2d》为基础,实现了用Viewport实现在2D场景中显示3D内容的效果。这次我们继续用视口来实现在3D场景中显示一个2D场景的效果。
最终效果如下:

首先我们来复习一下上节课的内容,用视口在2D场景中显示一个3D场景需要那些步骤?
-
一个2D场景和一个3D场景
-
一个视口
-
用于绘制视口内容的“画布”
本教程的原理和上一个教程非常类似,只不过我们创建了一个Quad类型的MeshInstance,用其Material下的Texture作为渲染目标,即所谓的画布。
先看一下2D场景:

和上个教程一样,勾选Camera2D
的Current
属性。
旋转的图标代码:
extends Sprite
func _process(delta):
rotation_degrees += delta*100.0
再看一下3D场景:

"QuadMesh"是1个"Quad"类型的MeshInstance
,使其旋转的代码如下:
extends MeshInstance
func _process(delta):
rotation_degrees.y -= delta*60.0
小结: 依然是两个简单的场景。接下来我们把2D场景嵌入到3D场景中
-
画布
即"QuadMesh"
-
添加视口
添加视口,命名为“Viewport_for_2dScene”,把刚才的那个原始2D场景直接实例化为视口的子场景。将视口的
Size
属性设为x
400y
400(默认为0,0),注意将Own World
选项勾选。或者你也可以为视口创建一个World
。这一步的作用就是将视口的子树分离成一个独立的世界。 -
把视口绘制到画布上
和之前稍有不同的是,我们要先为QuadMesh设置一下
Geometry
的Material Override
属性。

脚本实现如下:
extends Viewport
func _ready():
var mesh:MeshInstance = get_node("../QuadMesh")
mesh.material_override.albedo_texture = get_texture()
网友评论