diff --git a/src/health.cpp b/src/health.cpp new file mode 100644 index 0000000..7839d88 --- /dev/null +++ b/src/health.cpp @@ -0,0 +1,47 @@ +#include "health.hpp" +#include "utils/godot_macros.h" +#include +#include +#include + +namespace godot { +void Health::_bind_methods() { +#define CLASSNAME Health + GDPROPERTY(max_health, Variant::INT); + ClassDB::add_signal("Health", MethodInfo("damage", PropertyInfo(Variant::INT, "delta"), PropertyInfo(Variant::INT, "remaining"))); + ClassDB::add_signal("Health", MethodInfo("heal", PropertyInfo(Variant::INT, "delta"), PropertyInfo(Variant::INT, "remaining"))); + ClassDB::add_signal("Health", MethodInfo("health_changed", PropertyInfo(Variant::INT, "delta"), PropertyInfo(Variant::INT, "remaining"))); + ClassDB::add_signal("Health", MethodInfo("death", PropertyInfo(Variant::INT, "delta"))); +} + +void Health::_enter_tree() { + this->health = this->max_health; +} + +void Health::damage(int amount) { + this->health -= amount; + this->emit_signal("damage", amount, this->health); + this->emit_signal("health_changed", -amount, this->health); + if(this->health <= 0) { + this->emit_signal("death", amount); + } +} + +void Health::heal(int amount) { + this->health = std::min(this->health + amount, this->max_health); + this->emit_signal("health_changed", amount, this->health); + this->emit_signal("heal", amount, this->health); +} + +int Health::get_health() const { + return this->health; +} + +void Health::set_max_health(int max_health) { + this->max_health = std::abs(max_health); +} + +int Health::get_max_health() const { + return this->max_health; +} +} diff --git a/src/health.hpp b/src/health.hpp new file mode 100644 index 0000000..3cdf85b --- /dev/null +++ b/src/health.hpp @@ -0,0 +1,30 @@ +#ifndef HEALTH_HPP +#define HEALTH_HPP + +#include + +namespace godot { +class Health : public Node { + GDCLASS(Health, Node); + static void _bind_methods(); +public: + virtual void _enter_tree() override; + void damage(int amount); + void heal(int amount); + + int get_health() const; + void set_max_health(int max_health); + int get_max_health() const; +private: + int health{1}; + int max_health{1}; +}; + +class IHealthEntity { +public: + virtual Health *get_health() = 0; + virtual Health const *get_health() const = 0; +}; +} + +#endif // !HEALTH_HPP diff --git a/src/register_types.cpp b/src/register_types.cpp index ac91adf..289aca8 100644 --- a/src/register_types.cpp +++ b/src/register_types.cpp @@ -9,6 +9,7 @@ #include "utils/level.hpp" #include "utils/player_input.hpp" #include "utils/spawn_point.hpp" +#include "health.hpp" #include "player_character.hpp" #include "tunnels_game_mode.hpp" #include "tunnels_player.hpp" @@ -30,6 +31,7 @@ void initialize_gdextension_types(ModuleInitializationLevel p_level) ClassDB::register_class(); ClassDB::register_class(); ClassDB::register_class(); + ClassDB::register_class(); } extern "C"