-
Notifications
You must be signed in to change notification settings - Fork 16
bozar42 edited this page Apr 22, 2020
·
3 revisions
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. Below is the screenshot for Chapter 9.
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()
Godot engine has a built-in RandomNumberGenerator. In order to randomize NPC position, we need to tweak InitWorld._init_dwarf()
.
# InitWorld.gd
var _rng := RandomNumberGenerator.new()
func _ready() -> void:
_rng.randomize()
func _init_dwarf() -> void:
var dwarf: int = _rng.randi_range(3, 6)
var x: int
var y: int
while dwarf > 0:
x = _rng.randi_range(1, _new_DungeonSize.MAX_X - 1)
y = _rng.randi_range(1, _new_DungeonSize.MAX_Y - 1)
if _ref_DungeonBoard.has_sprite(_new_GroupName.WALL, x, y) \
or _ref_DungeonBoard.has_sprite(_new_GroupName.DWARF, x, y):
continue
_create_sprite(Dwarf, _new_GroupName.DWARF, x, y)
dwarf -= 1