GodotComponentTest/entities/Chest.cs

103 lines
2.8 KiB
C#

using Godot;
using System;
using System.Linq;
public class Chest : Entity
{
// resources
private PackedScene _goldBarScene = GD.Load<PackedScene>("res://entities/GoldBar.tscn");
public enum LidState
{
Closed,
Open
}
public LidState State = LidState.Closed;
public bool IsMouseOver = false;
private MeshInstance _mesh;
private SpatialMaterial _previousMaterial;
private AnimationPlayer _animationPlayer;
private Random _coinSpawnerRandom;
[Signal]
delegate void EntityClicked(Entity entity);
[Signal]
delegate void ChestOpened(Entity entity);
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
_mesh = GetNode<MeshInstance>("Armature/Skeleton/Chest");
_animationPlayer = GetNode<AnimationPlayer>("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 SpatialMaterial();
overrideMaterial.AlbedoColor = new Color(1, 0, 0);
_mesh.MaterialOverride = overrideMaterial;
}
public void OnAreaMouseExited()
{
IsMouseOver = false;
_mesh.MaterialOverride = null;
}
public void OnInteract()
{
_animationPlayer.Stop();
if (State == LidState.Closed)
{
State = LidState.Open;
_animationPlayer.Play("ChestOpen");
}
else
{
_animationPlayer.PlayBackwards("ChestOpen");
State = LidState.Closed;
}
}
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() * 2f - 1f) * 2
);
GetParent().AddChild(bar);
}
}
}