Home > Software design >  How can I fix all my area2D functions in Godot to not run on startup?
How can I fix all my area2D functions in Godot to not run on startup?

Time:03-11

Ok, I've been using Godot for a while now, and haven't really had any issues. But, after I added an area2D to detect the player and teleport them as shown below that I run into issues. Every time I start the game, the console shows that both of the functions have already been run, even though the starting location is nowhere near the area2Ds. In addition, because they run in enter -> exit order, it spawns me at the exit of the tunnel, instead of the start of the map.

func _on_Tunnel_body_entered(_body):
    print("entered_tunnel")
    global_position.x = 952.5
    global_position.y = 487

func _on_TunnelBack_body_entered(_body):
    print("exited_tunnel")
    global_position.x = 920
    global_position.y = 635

Any help would be appreciated!

CodePudding user response:

Are you, by chance, instancing the player character, adding it to the scene, and then setting its position (in that order)?

That is a common reason for this problem. What happens is that it collides with the areas once you add it to the scene but before you set its position.

To solve it set the global position before adding it to the scene.


You could temporarily disable the behavior by any of these means:

  • Temporarily changing the layers and mask to avoid the collision (you can do it with set_collision_layer_bit and set_collision_mask_bit).
  • Temporarily disabling collision shapes (by setting disabled to true. However, use set_deferred to avoid disabling it while Godot is still doing physics computations)
  • Temporarily adding collision exceptions (by calling add_collision_exception_with and remove_collision_exception_with).
  • Having a flag that you can check in the function that takes the signal to decide if it should take effect or not.
  • Connecting the signals from code once, so they are not connected beforehand.
  • Related