11.making-the-robot-die-when-touching-the-bat

Making the robot die when touching the bat

We have a slight problem with our bat: nothing happens when the bat touches the player.

Right now, the bat will attempt to chase the robot, even when the robot is on top of it! And the robot doesn’t seem to mind at all.

To give touching the bat some consequences, we’ll add a fail state when the robot gets too close to the bat. This will give the player a reason to avoid the bat.

For now, we’ll reset the scene so the player can try to get past the bat again.

By now, you might have a good idea about how to do this.

We’ll add an Area2D dedicated to detecting when the robot gets too close to the bat, right before they collide.

Adding the damage area

Add an Area2D to the Bat scene, name it DamageArea, and give a circular collision shape a little larger than the bat’s shape.

We don’t have anything that should monitor the DamageArea, so we toggle off Monitorable.

The DamageArea should detect the robot, which is on collision layer 2. So be sure to set the Collision -> Mask accordingly.

Attach a script to the DamageArea, and let’s look at it in full.

extends Area2D


func _ready() -> void:
    connect("body_entered", self, "_on_body_entered")


func _on_body_entered(player: KinematicBody2D) -> void:
    # A quick and easy way to reset the running scene.
    get_tree().reload_current_scene()

The reload_current_scene() function is new here. You’ve seen how to exit games using get_tree().quit() in the slideshow series, and this is another useful function you can use to reset levels.

You’d probably have something a bit more complex in a commercial game. But for prototypes or even simple arcade games, this is perfect.

You can run the Level scene to see the scene reload when the robot gets too close to the bat.

Other fail states

Having a dedicated damage area is useful because we can alter its behavior.

Instead of reloading the scene, we could reduce the robot’s health.

func _on_player_entered(player: KinematicBody2D) -> void:
    player.health -= 1

Of course, we’d also need to add a health system to our robot for this to work.

Perhaps we’d also implement a push-back mechanic to prevent the robot from staying in the area, but this is beyond the scope of this series.

For now, it’s time to expand the levels so we can put multiple bats and disappearing platforms in it.

In the next lesson, you will learn how to use the last kind of physics body: the rigid body. We will use it to make a rock the player can push to activate pressure plates and open doors.

The Code

Here’s the current code for the bat so far.

extends Area2D


func _ready() -> void:
    connect("body_entered", self, "_on_body_entered")


func _on_body_entered(player: KinematicBody2D) -> void:
    # A quick and easy way to reset the running scene.
    get_tree().reload_current_scene()