GodotComponentTest/components/ClickableComponent.cs

47 lines
1.5 KiB
C#
Raw Permalink Normal View History

using System;
using Godot;
using GoDotLog;
2023-11-18 22:32:57 +01:00
public class ClickableComponent : Spatial {
[Export] public string ClickName = "ClickName";
[Signal]
delegate void Clicked();
2023-11-18 22:32:57 +01:00
public bool IsMouseOver = false;
// private members
private CollisionObject _collisionObject;
// Called when the node enters the scene tree for the first time.
2023-11-18 22:32:57 +01:00
public override void _Ready() {
_collisionObject = (CollisionObject)FindNode("Area", false);
2023-11-18 22:32:57 +01:00
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,
2023-11-18 22:32:57 +01:00
int shapeIndex) {
if (IsMouseOver && inputEvent is InputEventMouseButton) {
InputEventMouseButton mouseButtonEvent = (InputEventMouseButton)inputEvent;
2023-11-18 22:32:57 +01:00
if (mouseButtonEvent.ButtonIndex == 1 && mouseButtonEvent.Pressed) {
GD.Print("Clicked on Clickable Component!");
EmitSignal("Clicked", this);
}
}
}
2023-11-18 22:32:57 +01:00
public void OnAreaMouseEntered() {
IsMouseOver = true;
}
2023-11-18 22:32:57 +01:00
public void OnAreaMouseExited() {
IsMouseOver = false;
}
}