我有来自第一级场景的 ParallaxBackground、Buildings 和 TileMap 节点。我会有几十个级别。我还有一个单独的小地图场景。我想使用脚本将上述三个节点连接到这个场景。
这是我目前的代码:
extends SubViewport
@onready var camera = $Camera2D
var level_scene = preload("res://Scens/Levels/Level0/Level_0.tscn").instantiate()
var Background
var Buildings
var Tile_Map
var level = Global.level:
set(value):
level = value
Background = level_scene.get_node("ParallaxBG")
Buildings = level_scene.get_node("Buildings")
Tile_Map = level_scene.get_node("TileMap")
func _physics_process(_delta):
camera.position = Global.player_position
if Input.is_action_just_pressed("action"):
$".".add_child(Background)
$".".add_child(Buildings)
$".".add_child(Tile_Map)
level = 1
我收到错误“无效调用。基本 PackedScene 中不存在函数‘get_node’”。
我对 Godot 4 还是新手。所以我不知道如何解决这个问题。预先感谢您。
您遇到的错误是因为 PackedScene 实例不像常规节点那样直接具有子节点,您需要首先实例化场景才能访问其节点。我建议这样的:
extends SubViewport
@onready var camera = $Camera2D
var level_scenes = [
preload("res://Scens/Levels/Level0/Level_0.tscn")
]
var current_level_scene = null
var Background
var Buildings
var Tile_Map
func _ready():
load_level(0) # Load the initial level
func load_level(level_index):
if current_level_scene:
current_level_scene.queue_free()
current_level_scene = level_scenes[level_index].instantiate()
add_child(current_level_scene)
Background = current_level_scene.get_node("ParallaxBG")
Buildings = current_level_scene.get_node("Buildings")
Tile_Map = current_level_scene.get_node("TileMap")
func _physics_process(_delta):
camera.position = Global.player_position
# Example: Load the next level when a condition is met
if some_condition:
load_level(1) # Load the second level
获取最新信息的最佳地点是Godot 论坛。希望这有帮助:-)