Skip to content

Commit 3db100e

Browse files
committed
Find coin nodes by their group
Previously, game_logic.gd walked recursively over all nodes in the tree, counting those which are an instance of the Coin script. A more idiomatic way to do this is to place coins into a group, and then count how many nodes are in that group. This will also make it easier to have some coins that don't count towards the goal, by having those coins not be in this group.
1 parent 6ec78a9 commit 3db100e

File tree

3 files changed

+3
-11
lines changed

3 files changed

+3
-11
lines changed

components/coin/coin.tscn

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
[sub_resource type="CircleShape2D" id="CircleShape2D_5w0o8"]
77
radius = 46.72
88

9-
[node name="Coin" type="Area2D"]
9+
[node name="Coin" type="Area2D" groups=["coins"]]
1010
collision_layer = 2
1111
script = ExtResource("1_4bks0")
1212

project.godot

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ window/stretch/mode="canvas_items"
3232
[global_group]
3333

3434
players=""
35+
coins="Coins that must be collected to win the level"
3536

3637
[input]
3738

scripts/rules_goals/game_logic.gd

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,6 @@ func _set_lives(new_lives):
4444
Global.lives = lives
4545

4646

47-
func _get_all_coins(node, accumulator = []):
48-
if node is Coin:
49-
accumulator.append(node)
50-
for child in node.get_children():
51-
_get_all_coins(child, accumulator)
52-
53-
5447
# Called when the node enters the scene tree for the first time.
5548
func _ready():
5649
if Engine.is_editor_hint():
@@ -65,9 +58,7 @@ func _ready():
6558
if win_by_collecting_coins:
6659
Global.coin_collected.connect(_on_coin_collected)
6760
if coins_to_win == 0:
68-
var coins = []
69-
_get_all_coins(get_parent(), coins)
70-
coins_to_win = coins.size()
61+
coins_to_win = get_tree().get_node_count_in_group(&"coins")
7162
if win_by_reaching_flag:
7263
Global.flag_raised.connect(_on_flag_raised)
7364

0 commit comments

Comments
 (0)