Collecting Items

Add items and to be collected in Godot. This lab is good to pair with the Rewards lab.

1. Setting up the Godot Project

2. Add Items

3. Update the Scene Manager

4. Add a third item

5. Documentation

Full ItemManager.gd script

extends Area2D

# support for multiple item types
export var item_type = "apple"
# duplicate scene and replace art for new items

# when item is collected send signal to scene manager and update metrics
signal item_collected

# prevents item being collected multiple times
var item_is_collected = false


# when player body enters item area -- area2d does not cause collisions

func _on_Item_body_entered(_body):
	
	# this assumes layer/mask setup only allows collisions with player
	if not item_is_collected:
		# prevent multiple collections during animation
		item_is_collected = true
		$AnimatedSprite.play('Collected')
		$AnimatedSprite.frame = 0 # make sure it plays from beginning
		
		# emit signal to add to global item count
		emit_signal('item_collected', item_type)
		
		# remove comment to play sfx
		# $CollectedSound.play()

# when the collected animation finishing play, remove the item
func _on_AnimatedSprite_animation_finished():
	if item_is_collected:
		queue_free()

Add to SceneManager.gd

# update Global based on items, update metrics display

func _on_item_collected(item_type):
	if item_type == 'apple':
		Global.item_count = Global.item_count + 1

	if item_type == 'life' and Global.player_lives < Global.total_lives:
		Global.player_lives = Global.player_lives + 1
	
	metrics.update_display()