From 898877f09808691a5e5d45850d27ae85f270db16 Mon Sep 17 00:00:00 2001 From: David Luevano Alvarado Date: Thu, 2 Jun 2022 02:35:03 -0600 Subject: add food system --- src/entities/food/scripts/food.gd | 23 ++++++++++++++++++ src/entities/food/scripts/food_manager.gd | 39 +++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/entities/food/scripts/food.gd create mode 100644 src/entities/food/scripts/food_manager.gd (limited to 'src/entities/food/scripts') diff --git a/src/entities/food/scripts/food.gd b/src/entities/food/scripts/food.gd new file mode 100644 index 0000000..1689837 --- /dev/null +++ b/src/entities/food/scripts/food.gd @@ -0,0 +1,23 @@ +class_name Food +extends Area2D + +enum Type { + APPLE +} + +var _type_texture: Dictionary = { + Type.APPLE: preload("res://entities/food/sprites/apple.png") +} + +export(Type) var TYPE +onready var _sprite: Sprite = $Sprite + + +func _ready(): + connect("body_entered", self, "_on_body_entered") + _sprite.texture = _type_texture[TYPE] + + +func _on_body_entered(body: Node) -> void: + Event.emit_signal("food_eaten", TYPE) + queue_free() \ No newline at end of file diff --git a/src/entities/food/scripts/food_manager.gd b/src/entities/food/scripts/food_manager.gd new file mode 100644 index 0000000..20772db --- /dev/null +++ b/src/entities/food/scripts/food_manager.gd @@ -0,0 +1,39 @@ +class_name FoodManager +extends Node2D + +export(PackedScene) var FOOD: PackedScene + +var max_apples: int = 10 +var current_apples: int = 0 + + +func _ready(): + Event.connect("food_eaten", self, "_on_food_eaten") + randomize() + + +func _process(delta) -> void: + if current_apples < max_apples: + _place_new_food() + current_apples += 1 + + +func _place_new_food() -> void: + var food: Area2D = FOOD.instance() + Event.emit_signal("food_placing_new_food", food.TYPE) + var position: Vector2 = _get_random_pos() + food.global_position = position + add_child(food) + Event.emit_signal("food_placed_new_food", food.TYPE) + + +func _get_random_pos() -> Vector2: + var screen_size: Vector2 = get_viewport().get_visible_rect().size + var temp_x: float = randf() * screen_size.x - screen_size.x / 2.0 + var temp_y: float = randf() * screen_size.y - screen_size.y / 2.0 + + return Vector2(temp_x, temp_y) + + +func _on_food_eaten(type: int) -> void: + current_apples -= 1 \ No newline at end of file -- cgit v1.2.3-70-g09d2