Skip to content
bozar42 edited this page Apr 16, 2020 · 3 revisions

09: Reload Or Randomize The Game

Source code.

In this chapter, we will add two more features to the demo: press Space to reload game and put NPCs in random positions whenever the game starts.

Press Space To Reload

Open Project Settings/Input Map, add a new action reload and bind Space to it. Let PCMove.gd responds to the action.

# PCMove.gd

func _unhandled_input(event: InputEvent) -> void:
    # Remain the same.

    if _is_move_input(event):
        # Remain the same.
    elif _is_reload_input(event):
        print("reload")


func _is_reload_input(event: InputEvent) -> bool:
    if event.is_action_pressed(_new_InputName.RELOAD):
        return true
    return false

Add ReloadGame as a child node to PCMove. Also attach a script to the node. Let PCMove.gd call ReloadGame.reload().

# ReloadGame.gd

func reload() -> void:
    var new_scene: Node2D = load(PATH_TO_MAIN).instance()
    var old_scene: Node2D = get_tree().current_scene

    get_tree().root.add_child(new_scene)
    get_tree().current_scene = new_scene

    get_tree().root.remove_child(old_scene)
    old_scene.queue_free()

Clone this wiki locally