GodotComponentTest/entities/Tree.cs

105 lines
2.8 KiB
C#

using Godot;
using System;
using System.Diagnostics;
using GodotComponentTest.components;
using GodotComponentTest.entities;
public class Tree : Entity, IInteractionInterface
{
[Export] public float ChopDuration = 2;
public bool IsMouseOver;
private MeshInstance _geometry;
private AnimationPlayer _animationPlayer;
private float _health = 100;
private bool _isBeingChopped;
private InteractionComponent _interactionComponent;
public InteractionComponent InteractionComponent
{
get => _interactionComponent;
set => _interactionComponent = value;
}
[Signal]
delegate void EntityClicked(Entity entity);
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
_geometry = GetNode<MeshInstance>("Geometry");
Debug.Assert(_geometry != null);
_animationPlayer = GetNode<AnimationPlayer>("AnimationPlayer");
Debug.Assert(_animationPlayer != null);
_animationPlayer.CurrentAnimation = "Idle";
_animationPlayer.Play();
Connect("input_event", this, nameof(OnAreaInputEvent));
Connect("mouse_entered", this, nameof(OnAreaMouseEntered));
Connect("mouse_exited", this, nameof(OnAreaMouseExited));
}
public override void _Process(float delta)
{
base._Process(delta);
if (_isBeingChopped)
{
_health = Math.Max(0, _health - delta * 100 / ChopDuration);
}
if (_health == 0)
{
QueueFree();
}
}
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);
_geometry.MaterialOverride = overrideMaterial;
}
public void OnAreaMouseExited()
{
IsMouseOver = false;
_geometry.MaterialOverride = null;
}
public void OnInteractionStart()
{
GD.Print("Starting tree animationplayer");
_animationPlayer.CurrentAnimation = "TreeShake";
_animationPlayer.Seek(0);
_animationPlayer.Play();
_isBeingChopped = true;
}
public void OnInteractionEnd()
{
_animationPlayer.CurrentAnimation = "Idle";
_animationPlayer.Seek(0);
_animationPlayer.Stop();
_isBeingChopped = false;
}
}