A Minecraft style clone in Godot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

79 lines
2.3 KiB

class_name Inventory
extends Control
@export var inventory_resource: InventoryResource
@export var item_rect_scene: PackedScene
@export var grid_container: GridContainer
@export var max_items: int = 40 # 4 rows of 10
@export var highlight_theme: Resource
var selected_item: int = 0
func _input(event: InputEvent) -> void:
if event.is_action_pressed("open_inventory"):
toggle_inventory()
func _ready() -> void:
update_inventory_with_resource()
refresh_inventory_grid()
InventoryManager.item_added.connect(_on_item_added) # Should be added after update_inventory_with_resource()
InventoryManager.item_removed.connect(_on_item_removed) # Should be added after update_inventory_with_resource()
func create_item_cell(item_resource: DBItemResource) -> void:
var item_rect: InventoryItemRect = item_rect_scene.instantiate()
grid_container.add_child(item_rect)
item_rect.init(item_resource, highlight_theme)
func find_item_rect(item_resource: DBItemResource) -> InventoryItemRect:
var rect: InventoryItemRect = null
for item_rect: InventoryItemRect in grid_container.get_children():
if item_rect.item_resource == null: continue
if item_rect.item_resource.id == item_resource.id:
rect = item_rect
break
return rect
func refresh_inventory_grid() -> void:
for item: InventoryItemRect in grid_container.get_children():
item.queue_free()
for item: DBItemResource in InventoryManager.inventory:
create_item_cell(item)
var empty_cells: int = InventoryManager.max_inventory_items - InventoryManager.inventory.size()
for _i: int in range(empty_cells):
create_item_cell(null)
func toggle_inventory() -> void:
visible = not visible
if visible:
Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
InventoryManager.inventory_opened.emit()
get_tree().paused = true
else:
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
InventoryManager.inventory_closed.emit()
get_tree().paused = false
## Add any items from the existing inventory resource
func update_inventory_with_resource() -> void:
if inventory_resource == null:
return
for item_resource: DBItemResource in inventory_resource.inventory:
InventoryManager.add_to_inventory.emit(item_resource.id, item_resource.amount)
func _on_item_added(_item_id: String, _amount: int) -> void:
refresh_inventory_grid()
func _on_item_removed(_item_id: String, _amount: int) -> void:
refresh_inventory_grid()