How to use reusable hitbox class

Godot Version

<stable4.2>

Question

<Im trying to implement hitbox/hurtbox class to my 2d platformer project. How do you set different variable of damage for each enemy nodes for hitbox script?

my current hitbox script:

@icon("res://entities/node/HitBox.svg")
class_name HitBox
extends Area2D

@export var damage := 10


func get_damage() -> int:
	print("damage")
	return damage + randi() % 7 - 3

hitbox script:

@icon("res://entities/node/HurtBox.svg")
class_name HurtBox
extends Area2D


func _ready() -> void:
	connect("area_entered", Callable(self, "_on_area_entered"))


func _on_area_entered(hitbox: HitBox) -> void:
	if owner.has_method("take_damage"):
		owner.take_damage(hitbox.get_damage())
	if owner.has_method("knock_back"):
		owner.knock_back()

the @export variable can be set in editor from the inspector. It seems like you’ve got this, what is going wrong exactly? Could you show a scene tree of something with a hit/hurt box?

well there is nothing wrong with script. I just want to know how to set different damage variable or function in hitbox. because hitbox class script will be shared with all attached node, if i understand correctly. @export var damage := 10 is for player projectile. if I want to set damage = 20 for enemy, how would i do it?

Exported variables show up in the inspector, when editing it’s specific to the node. So where ever your player’s hitbox you’d leave at 10, then the enemy’s hitbox you can set to 20 from the inspector.

Here’s what it will look like.

2024-05-04-010545_277x307_scrot

extends Node3D

@export var my_exported_var: int = 10

ohh i see, so i can set different damage value in different nodes. i did not know that.
can you teach me how to call some function in parent node? for example, I have a function that instantiate some effect when area entered. or i want to change player state when hurtbox area entered.

func _on_area_entered(hitbox: HitBox) -> void:
	if owner.has_method("take_damage"):
		owner.take_damage(hitbox.get_damage())
	if owner.has_method("knock_back"):
		owner.knock_back()
	if owner.has_method("grab"):
		owner.grab()

I only wat call take_damage function when bullet hitbox entered, and knock_back function when player entered. how do you call each method separately.

when using hitbox/hurtbox class, do you have to extend script?

I would probably use metadata, again in the inspector at the very bottom you can add any extra data. Maybe a “do_knockback” bool for the player. You would check for meta data like so

func _on_area_entered(hitbox: HitBox) -> void:
	var do_knockback = hitbox.get_meta("do_knockback", false)
	if owner.has_method("take_damage"):
		owner.take_damage(hitbox.get_damage())
	if owner.has_method("knock_back") and do_knockback:
		owner.knock_back()
	if owner.has_method("grab"):
		owner.grab()

Though metadata is hard to keep track of and easy to error by misspelling, for boolean data groups work just as well and have similar flaws.