0 votes

I come from a programming background and so I am trying to use Godot mostly through programming.

I wanted to create my own type of node "Boulder" and detect when it collides with my player.

I created the boulder node using only GDScript:

# boulder.gd
class_name Boulder

var area

func _ready():
    # Set up the collision for the boulder
    area = Area2D.new()
    # (omitted) set sollision mask, collision shape, etc

Then I created my player through the editor.
I added an Area2D node to my player, and used the edtior to connect the area_entered signal to the player GDscript:

# Player.gd
func _on_Area2D_area_entered(boulder: Boulder):
    print("Collided with: ", boulder)

I then have a scene where I spawn a Boulder so that it will fall onto the player.

However, when they collide the boulder value passed to _on_Area2D_area_entered is null.

Not sure what is happening here.

Godot version Godot Engine v3.3.2.stable.official
in Engine by (15 points)

1 Answer

+1 vote
Best answer

the area_entered signal has the Area that entered has an argument (the one stored in area in your script) which is not a Boulder (what does Boulder extends?). You are type casting the Area as a Boulder in your method, resulting in null.

by (728 points)
selected by

Thank you! I didn't realize the type casting would cause the result to be null.

If I change Boulder to extend Area2D the above code should work as expected?

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.