GodotComponentTest/components/ClickableComponent.cs

55 lines
1.5 KiB
C#

using System;
using Godot;
using GoDotLog;
public class ClickableComponent : Spatial
{
[Export] public string ClickName = "ClickName";
[Signal]
delegate void Clicked();
public bool IsMouseOver = false;
// private members
private CollisionObject _collisionObject;
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
_collisionObject = (CollisionObject)FindNode("Area", false);
if (_collisionObject == null)
{
GD.PrintErr("Error: could not find Area for Clickable Component!");
return;
}
_collisionObject.Connect("input_event", this, nameof(OnAreaInputEvent));
_collisionObject.Connect("mouse_entered", this, nameof(OnAreaMouseEntered));
_collisionObject.Connect("mouse_exited", this, nameof(OnAreaMouseExited));
}
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)
{
GD.Print("Clicked on Clickable Component!");
EmitSignal("Clicked", this);
}
}
}
public void OnAreaMouseEntered()
{
IsMouseOver = true;
}
public void OnAreaMouseExited()
{
IsMouseOver = false;
}
}