cirnogodot/Scripts/Selector.cs

108 lines
2.7 KiB
C#
Raw Normal View History

2025-01-30 08:34:09 +01:00
using Godot;
using System;
using System.Collections.Generic;
public partial class Selector : Node2D
{
private Interactable _lastInteractable;
private List<Interactable> _interactables = new List<Interactable>();
private int _selectedInteractable;
2025-01-30 15:45:29 +01:00
[Signal]
public delegate void SelectedItemInteractableChangedEventHandler(Interactable interactable);
public Interactable SelectedInteractable
{
get =>
_interactables.Count > 0
? _selectedInteractable >= _interactables.Count
? _interactables[^1]
: _interactables[_selectedInteractable]
: null;
set
{
// Passing null deselects the interactable
if (value == null)
{
_selectedInteractable = -1;
NotifyChanged(null);
return;
}
// If it's already in the list, set the current one to it, otherwise add it
if (!_interactables.Contains(value))
{
AddInteractable(value);
}
_selectedInteractable = _interactables.IndexOf(value);
NotifyChanged(value);
}
}
public override void _Process(double delta)
{
2025-01-30 15:58:55 +01:00
if (Input.IsActionJustPressed("scan"))
2025-01-30 15:45:29 +01:00
{
_selectedInteractable += 1;
2025-01-30 15:58:55 +01:00
if (_selectedInteractable >= _interactables.Count)
{
_selectedInteractable = 0;
}
SelectedInteractable = _interactables[_selectedInteractable];
2025-01-30 15:45:29 +01:00
UpdatePosition();
2025-01-30 15:58:55 +01:00
2025-01-30 15:45:29 +01:00
}
}
private void NotifyChanged(Interactable interactable)
{
EmitSignal(nameof(SelectedItemInteractableChanged), interactable);
}
2025-01-30 08:34:09 +01:00
public void AddInteractable(Interactable interactable)
{
if (!_interactables.Contains(interactable)) {
_interactables.Add(interactable);
2025-01-30 15:45:29 +01:00
if (_interactables.Count == 1)
{
_selectedInteractable = 0;
}
2025-01-30 08:34:09 +01:00
}
2025-01-30 15:45:29 +01:00
UpdatePosition();
2025-01-30 08:34:09 +01:00
}
2025-01-30 15:45:29 +01:00
public void RemoveInteractable(Interactable interactable)
2025-01-30 08:34:09 +01:00
{
2025-01-30 15:45:29 +01:00
if (_interactables.Contains(interactable))
{
_interactables.Remove(interactable);
}
UpdatePosition();
}
2025-01-30 08:34:09 +01:00
2025-01-30 15:45:29 +01:00
public void Deselect()
{
_selectedInteractable = -1;
this.Visible = false;
2025-01-30 08:34:09 +01:00
}
2025-01-30 15:45:29 +01:00
public void UpdatePosition()
{
if (SelectedInteractable != null)
{
this.Position = SelectedInteractable.Position;
this.Visible = true;
}
else
{
this.Visible = false;
}
}
2025-01-30 08:34:09 +01:00
}