using Godot; using System; using System.Collections.Generic; using Godot.Collections; using GodotComponentTest.components; using GodotComponentTest.entities; using Array = System.Array; using NodePair = System.Tuple; public class InteractionSystem : Node { private List _interactionPairs; // Called when the node enters the scene tree for the first time. public override void _Ready() { _interactionPairs = new List(); } public override void _Process(float delta) { base._Process(delta); List invalidInteractionPairs = new List(); foreach (Tuple pair in _interactionPairs) { Node nodeA = pair.Item1; Node nodeB = pair.Item2; if (nodeA == null || nodeA.IsQueuedForDeletion() || nodeB == null || nodeB.IsQueuedForDeletion()) { invalidInteractionPairs.Add(pair); } if (nodeA == null || nodeA.IsQueuedForDeletion()) { IInteractionInterface interactableB = nodeB as IInteractionInterface; if (interactableB != null) { interactableB.OnInteractionEnd(); interactableB.InteractionComponent = null; } } if (nodeB == null || nodeB.IsQueuedForDeletion()) { IInteractionInterface interactableA = nodeA as IInteractionInterface; if (interactableA != null) { interactableA.OnInteractionEnd(); interactableA.InteractionComponent = null; } } } foreach (NodePair pair in invalidInteractionPairs) { _interactionPairs.Remove(pair); } } public void OnStartInteraction(Entity owningEntity, Entity targetEntity) { InteractionComponent interactionComponent = new InteractionComponent(); interactionComponent.OwningEntity = owningEntity; interactionComponent.TargetEntity = targetEntity; ConnectInteractionSignals(owningEntity, interactionComponent); ConnectInteractionSignals(targetEntity, interactionComponent); interactionComponent.EmitSignal("InteractionStart"); NodePair pair = new NodePair(owningEntity, targetEntity); _interactionPairs.Add(new NodePair(owningEntity, targetEntity)); } private static void ConnectInteractionSignals(Entity entity, InteractionComponent interactionComponent) { IInteractionInterface interactable = entity as IInteractionInterface; if (interactable != null) { interactable.InteractionComponent = interactionComponent; interactionComponent.Connect("InteractionStart", entity, nameof(interactable.OnInteractionStart)); interactionComponent.Connect("InteractionEnd", entity, nameof(interactable.OnInteractionEnd)); } } }