104 lines
3.0 KiB
C#
104 lines
3.0 KiB
C#
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;
|
|
private Label _quantityLabel;
|
|
private Sprite2D _shadowSprite;
|
|
|
|
// 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();
|
|
|
|
// Get the Label node for quantity
|
|
if (HasNode("Label"))
|
|
{
|
|
_quantityLabel = GetNode<Label>("Label");
|
|
if (Quantity > 1)
|
|
_quantityLabel.Text = Quantity.ToString();
|
|
else
|
|
_quantityLabel.Text = string.Empty;
|
|
}
|
|
|
|
// Add or update shadow sprite
|
|
if (HasNode("ShadowSprite"))
|
|
{
|
|
_shadowSprite = GetNode<Sprite2D>("ShadowSprite");
|
|
_shadowSprite.Texture = _sprite.Texture;
|
|
_shadowSprite.Modulate = new Color(0, 0, 0, 0.5f);
|
|
_shadowSprite.Position = _sprite.Position + new Vector2(0, 6);
|
|
_shadowSprite.ZIndex = _sprite.ZIndex - 1;
|
|
}
|
|
else
|
|
{
|
|
_shadowSprite = new Sprite2D();
|
|
_shadowSprite.Scale = _sprite.Scale;
|
|
_shadowSprite.Name = "ShadowSprite";
|
|
_shadowSprite.Texture = _sprite.Texture;
|
|
_shadowSprite.Modulate = new Color(0, 0, 0, 0.5f);
|
|
_shadowSprite.Position = _sprite.Position + new Vector2(0, 6);
|
|
_shadowSprite.ZIndex = _sprite.ZIndex - 1;
|
|
AddChild(_shadowSprite);
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|
|
} |