using System.Linq; using Godot; using GodotComponentTest.components; using GodotComponentTest.entities; public class Chest : Entity, IInteractionInterface { // resources private readonly PackedScene _goldBarScene = GD.Load("res://entities/GoldBar.tscn"); public enum LidState { Closed, Open } public LidState State = LidState.Closed; public bool IsMouseOver; private MeshInstance _mesh; private AnimationPlayer _animationPlayer; public InteractionComponent InteractionComponent { get; set; } [Signal] private delegate void EntityClicked(Entity entity); [Signal] private delegate void ChestOpened(Entity entity); // Called when the node enters the scene tree for the first time. public override void _Ready() { _mesh = GetNode("Geometry/Skeleton/Chest"); _animationPlayer = GetNode("AnimationPlayer"); Connect("input_event", this, nameof(OnAreaInputEvent)); Connect("mouse_entered", this, nameof(OnAreaMouseEntered)); Connect("mouse_exited", this, nameof(OnAreaMouseExited)); Connect("ChestOpened", this, nameof(ChestOpened)); } public void OnAreaInputEvent(Node camera, InputEvent inputEvent, Vector3 position, Vector3 normal, int shapeIndex) { if (IsMouseOver && inputEvent is InputEventMouseButton) { InputEventMouseButton mouseButtonEvent = (InputEventMouseButton)inputEvent; if (mouseButtonEvent.ButtonIndex == 1 && mouseButtonEvent.Pressed) { EmitSignal("EntityClicked", this); } } } public void OnAreaMouseEntered() { IsMouseOver = true; SpatialMaterial overrideMaterial = new(); overrideMaterial.AlbedoColor = new Color(1, 0, 0); _mesh.MaterialOverride = overrideMaterial; } public void OnAreaMouseExited() { IsMouseOver = false; _mesh.MaterialOverride = null; } public void OnInteractionStart() { _animationPlayer.Stop(); if (State == LidState.Closed) { State = LidState.Open; _animationPlayer.Play("ChestOpen"); } else { _animationPlayer.PlayBackwards("ChestOpen"); State = LidState.Closed; } } public void OnInteractionEnd() { } public void OnChestOpened() { GD.Print("Chest now opened!"); foreach (int i in Enumerable.Range(0, 10)) { GoldBar bar = (GoldBar)_goldBarScene.Instance(); bar.Transform = new Transform(Transform.basis.Rotated(Vector3.Up, GD.Randf() * 2 * Mathf.Pi), Transform.origin + Vector3.Up * 0.8f); bar.Velocity = new Vector3( (GD.Randf() * 2f - 1f) * 2, 5 + GD.Randf() * 0.3f, (GD.Randf() * 2f - 1f) * 2 ); GetParent().AddChild(bar); } if (InteractionComponent != null) { InteractionComponent.EndInteraction(); } } }