Item pickup

This commit is contained in:
2025-08-29 12:33:10 +08:00
parent 850628ca72
commit fac5e5a597
12 changed files with 191 additions and 5 deletions

View File

@@ -71,7 +71,7 @@ public partial class BuildingRegistry : Node
return;
}
var dict = (Godot.Collections.Dictionary)json.Data;
var dict = json.Data.AsGodotDictionary();
foreach (string key in dict.Keys)
{

View File

@@ -0,0 +1,71 @@
using Godot;
namespace AceFieldNewHorizon.Scripts.System;
public partial class ItemPickup : Node2D
{
public const string PickupGroupName = "ItemPickupTarget";
[Export] public string ItemId { get; set; } = "";
[Export] public int Quantity { get; set; } = 1;
[Export] public bool Infinite { get; set; } = false;
private Sprite2D _sprite;
// Called when the node enters the scene tree
public override void _Ready()
{
var area = GetNode<Area2D>("Area2D");
area.BodyEntered += OnBodyEntered;
_sprite = GetNode<Sprite2D>("Sprite2D");
UpdateTexture();
}
private void UpdateTexture()
{
var file = FileAccess.Open("res://Data/ItemTextures.json", FileAccess.ModeFlags.Read);
if (file == null)
{
GD.PrintErr("Failed to open ItemTextures.json");
return;
}
var text = file.GetAsText();
file.Close();
var json = new Json();
var err = json.Parse(text);
if (err != Error.Ok)
{
GD.PrintErr(json.GetErrorMessage());
return;
}
var dict = json.Data.AsGodotDictionary();
if (!dict.TryGetValue(ItemId, out var value))
return;
var texturePath = value.AsString();
if (string.IsNullOrEmpty(texturePath))
return;
var texture = GD.Load<Texture2D>(texturePath);
if (texture == null)
return;
_sprite.Texture = texture;
}
private void OnBodyEntered(Node body)
{
if (body.IsInGroup(PickupGroupName))
{
if (body.HasMethod("AddItem"))
body.Call("AddItem", ItemId, Quantity);
if (!Infinite)
QueueFree(); // remove the pickup from the world
}
}
}

View File

@@ -0,0 +1 @@
uid://qgcue2doj2lf