Dealing damage and other interactions

Let's continue working on our previous project. So far, we have a player who shoots an arrow whenever we left click, so let's add some Enemies for him to shoot at.


Adding Projectile Collisions

For our enemy, let's create a new scene. A simple Node2D with an Area2D and Sprite2D as children will do just fine.

So now we just shoot our enemy and...

Nothing happens. That's because we haven't set our collisions yet!

Let's set our enemy on the Collision Layer 2, our projectile in layer 5, and have their Collision Masks interact with each other.

And now our projectile really has collisions!


Dealing damage

Whenever a projectile collides with an Object, it will try to call a method on it. Which method, you may ask? The one defined in its on_hit_call property.

Let's add a simple script to our enemy so it gets deleted when it gets hit by a projectile.

extends Node2D

func damage() -> void:
	queue_free()

Now we shoot and...

Nothing happens. That's because our method is incorrect!

Your selected method must follow a defined pattern, taking the projectile itself as a parameter:

extends Node2D

func damage(proj: Projectile2D) -> void:
	print("I took %d damage!" % proj.damage)
	queue_free()

Here you can access all the properties of the projectile that just collided with our enemy. Now let's shoot again and...

Nothing happens again. That's because we're calling the method on the wrong target.

You see, when a projectile collides with an Object, it will try to call its on_hit_call method on the target it has collided with. In this case, on our enemy's Area2D Node, and since it has no script, it will do nothing.

To fix this, we will have to set our script on the Area2D Node or we will have to tell the projectile to don't communicate with the collided object, and use its parent instead.

All Projectiles allows us to do this just by adding Area2D on the step group. After setting up the group, all colliding projectiles will directly communicate with Area2D's parent and, of course, this behavior can be chained.

Now our projectile can finally damage our enemy!