Trying to Generalize my Damage code

Godot Version

4.4.1

Question

Hello, I have been trying to code a very simple local multiplayer game, and I am trying to make it so when the character collides with the raycast of the other one, it takes damage. The raycast part is simple, however I am having dificulty in making it reference the other character when referring to the Health Variable of the character getting hit.


if $Player1/RayCast2D/Line2D.modulate == Color.RED and $Player1/RayCast2D.is_colliding():
  $Player1/RayCast2D/Line2D.modulate = Color.WHITE #Guarantes the Character deals only 1 damage
  $Player2.HEALTH -= 1

This is the code I have been using , but I would like to generalize it so that it works with any character hiting any other character. When the line is red it means the hitbox for the attack is active which is why I am verifying if it’s red. How could I solve this? `

Putting aside for a moment the question whether a RayCast2D is the optimal solution for this problem, you could use get_collider() to get what the RayCast2D is colliding with. Assuming your player script has a class name (for instance, Player), you could then use is figure out if the thing your ray is colliding with is a player. So something like this:

var ray : RayCast2D = null

func _physics_process(delta : float)->void:
    ...

    var col = ray.get_collider()
    if col != null:
        if col is Player:
            # Cast col to player and decrement health.

You could even generalize further and make something like a HealthComponent scene that you can add to whatever scene you’d like to be able to take damage, then check if the object you’re colliding with has that component. That way, your script doesn’t even have to know what the Player class is.

2 Likes