diff --git a/_subsections/sec03/lesson-30.org b/_subsections/sec03/lesson-30.org index d95da9a..7bdd58e 100644 --- a/_subsections/sec03/lesson-30.org +++ b/_subsections/sec03/lesson-30.org @@ -74,3 +74,85 @@ queue_free() #+end_src ** Game scene +*** preload assets +- using const to set builtin preload function + #+begin_src gdscript + const EXPLOSDE = preload("res://assets/explode.wav") + #+end_src + +*** add a PackedScene variable + - allows us to instantiate gem scenes + - export allows us to drag and drop the scene we want into the inspector + #+begin_src gdscript + @export var gem_scene: PackedScene + + # when time comes to use it + gem_scene.instantiate() + add_child(gem_scene) + #+end_src + + - otherwise we would have to preload it + #+begin_src gdscript + gem_scene = preload("res://somescene.tscn").instantiate() + add_child(gem_scene) + #+end_src + +*** use onready to add nodes in tree scene +#+begin_src gdscript +@onready var label: Label = $Label +@onready var timer: Timer = $Timer +@onready var audio_stream_player_2d: AudioStreamPlayer2D = $AudioStreamPlayer2D +#+end_src + +- these are all scenes in the Game tree +- use onready to attach them to variables for use in game script +- onready makes sure it's available so we dont end up with a null reference + +*** spawn gem at _ready +- in the ready function immediately call spawn_gem +- spawn Gem instantiates a gem scene and type casts it to a Gem class +- connect any signals +- set it's position +- add it as a child + #+begin_src gdscript + var new_gem: Gem = gem_scene.instantiate() + new_gem.on_gem_off_screen.connect(game_over) + new_gem.position = Vector2(xpos, ypos) + add_child(new_gem) + #+end_src + +*** stop all function +- stop the timer +- run through all children and set process to false + #+begin_src gdscript + timer.stop() + for child in get_children(): + child.set_process(false) + #+end_src + +*** turn off audio +- get references to audio and call 'stop' function +- you can also set another sound for ending and play that + +#+begin_src gdscript + audio_stream_player_2d.stop() + audio_stream_player_2d.stream = EXPLODE + audio_stream_player_2d.play() +#+end_src + +*** whenever timer times out spawn a gem +- we attached the timer to a signal to call a function that calls spawn gem + +*** when the paddle gets hit by a gem +- increase score +- set the position of where the paddle got hit to the audio and play a sound +- free up the hit object (the gem) + +#+begin_src gdscript +func _on_padd_area_entered(area: Area2D) -> void: + _score += 1 + label.text = "%05d" % _score + audio_stream_player_2d.position = area.position + audio_stream_player_2d.play() + area.queue_free() +#+end_src