Create a Catch the egg game in Godot engine – 5

In this part we are going to spawn the eggs randomly. Right now our basket detects the egg dropped inside. Before going to spawn the eggs, we are going to remove the dropped eggs from the scene. So let’s start.

We already attached a script to the basket node. It looks like this.

extends KinematicBody2D

func _ready():
    print("test")
    pass


func _on_Area2D_body_enter( body ):
    print("Dropped inside")
    pass # replace with function body

In the signal callback _on_Area2D_body_enter, we get the body which entered into the area. This body will be the egg.

So change the callback to look like this.

func _on_Area2D_body_enter( body ):
    body.queue_free()

This will remove the egg when it is dropped inside the basket. Great! the major part of our game is done.

But what happens to the egg which are dropped to the ground. It will stay there because we didn’t code any logic to handle that situation. To do that, create a new script for the egg node.

Similar to how we added the area_enter signal callback for the basket, add a body_enter signal callback on the egg node.

After doing that, we get a callback method in the egg script. Add a print statement to check the collided body name.

Make sure you have set the Contacts Reported to 1 and enable the Contact Monitor to true for the egg node. Otherwise the print won’t work.

func _on_egg_body_enter( body ):
    print(body.get_name())

Now, when the egg drops to the ground, we get the print “ground”. Replace it with this

func _on_egg_body_enter( body ):
    if(body.get_name()=="ground"):
        queue_free()

and we get the result we wanted, the egg disappears on hitting the ground.

Also Read:   How to save and load game in Godot Engine

Controlling the basket

We need to check the mouse x position and assign it to the basket, so that it moves when we move the mouse. The basket script looks like this now,

 

extends KinematicBody2D

func _ready():
    set_process(true)


func _process(delta):
    var mouse_pos = get_viewport().get_mouse_pos()
    var this_pos = get_pos()
    this_pos.x = mouse_pos.x
    set_pos(this_pos)


func _on_Area2D_body_enter( b ):
    if(b.get_name() == "egg"):
        b.queue_free()

We can see that the signal callback now includes a check if it is colliding with the egg. This will not work when we spawn multiple eggs or if the name changes. To avoid that we will be adding this egg to a group. Select the egg node and click on the Group button on the top of the hierarchy. Type “eggs” and add the group. Now change the above callback like this,

func _on_Area2D_body_enter( b ):
    if(b.is_in_group("eggs")):
        b.queue_free()

Great, it works the same as before but this time, it checks the group instead of the name.

Creating the egg subscene

To spawn multiple eggs, we need to convert our egg node to a packed scene. To do that, select the egg node, and click the Create Scene From Node(s) button.

Convert to subscene

Name the scene as egg.tscn inside the scenes folder. We can now delete the egg node from the hierarchy. Then create a new ‘Node’ as the child of ‘main’ and rename it to EggSpawner. Also add a script to it. This script is responsible for the spawning of the eggs.

Also Read:   Direction vectors in Godot Engine

 

extends Node

export var delay = 1
export (PackedScene) var egg

var timer = 0

func _ready():
    set_process(true)

func _process(delta):
    timer += delta
    if(timer >= delay):
        timer = 0
        create_egg()

func create_egg():
    print("Creating egg")
    var e = egg.instance()
    e.add_to_group("eggs")
    add_child(e)
    e.set_pos(Vector2(rand_range(0,get_viewport().get_visible_rect().size.x),0))

The script is self explanatory. We export two variables to edit its behaviour inside the editor. The first one is spawn delay which is in seconds and it is default to 1. The next one is to select a PackedScene. This PackedScene is instanced multiple times. Select the EggSpawner node and we can see it in the properties panel. Browse and select the egg.tscn scene. The create_egg function create instances of the egg scene and add it to the scene as well as to the “eggs” group. The x position is a random one ranging from 0 to the viewport width. That’s all, press Play and enjoy the game.

This part concludes the Catch the egg game tutorial series. It was only meant to show the workflow and just the basics to quick start into the Godot engine. You can always apply your thoughts and extend this with other features. Thanks for reading.

The full source code is available here.
https://github.com/vinod8990/godot_example_catch_the_egg

Never miss any content from Codetuto!

Subscribe to Codetuto Newsletter and be the first to recieve our latest posts and tutorials

Subscribe Now For Free

[Total: 5    Average: 4/5]
  • Kishore Srinivas

    can you guys do a platformer tutorial in Godot ? that will be great and awesome godot tutorial by the way.

    • Vinod

      Will be doing a new one. Thanks

  • Carlos Sánchez

    https://uploads.disquscdn.com/images/0bbdddb564547e6007661e538ad2c9f926459bafa2edeeea3574c8116adb0f52.png

    Hello! People, maybe someone still over here and can help me with my problem

    I’m pretty new trying to use godot so, what could be the reasons i have this error

    “Nonexistent function ‘instance’ in base ‘Nil’

    i do a little of research and i found that it is pretty common with function but i don’t know how to resolve this.

    Thanks!

    P.D No native speaker, sorry for any grammatical mistake

    • Vinod

      Ok. If we try to learn something from the error, which says.
      Nonexistent function ‘instance’ in base ‘Nil’

      It tells us that there is no ‘instance’ function in ‘Nil’ – which means null.
      So the ‘egg’ variable in your script is null. That means you may not have set the PackedScene path in the editor inspector for this object.

      “Select the EggSpawner node and we can see it in the properties panel. Browse and select the egg.tscn scene.”

      • Carlos Sánchez

        Thank you so much, that solved my issue

        Well i have to say your tutorials are solid way of learning, thanks for take your time to teach

        Thanks again! , I’ll try the other tutorials

  • moein rahimi

    hi,can’t move basket from middle to left, basket just stuck in the middle, i can move it from middle to right,

    • Vinod

      Check if anything colliding with the basket blocking the movement.
      Thanks

  • ax xa

    func _process(delta):
    var mouse_pos = get_viewport().get_mouse_pos()
    var this_pos = get_pos()
    this_pos.x = mouse_pos.x
    set_pos(this_pos)

    Problem: i run this code and the basket won’t show anymore.

    Another way to do it with other input?

  • ax xa

    Create new scene from node(s),Does anyone know where this icon has gone? It used to be on the Scene tab but with 2.1 it’s not there anymore.
    Answer:
    It’s now under
    right click object -> Save Branch As Scene.

    • ax xa

      Answer:
      It’s now under
      right click object -> Save Branch As Scene.

  • Heckingson Jumbo

    Thanks Man! This was really helpful, God bless!

  • Dave Vaughan

    Following along ( you jumped a bit when doing the mouse movement code) anyway I’ve found that moving the mouse too quickly makes my basket disappear never to return.
    Any ideas ?

    • Dave Vaughan

      Just incase anyone else comes across this problem, I hadnt seen the group bit, where we check that the egg scene has a group (tag) associated with it. I’d initially fixed my issue by changing the detection to if(body.get_name() != “basket”): and while that worked, its notcompatable directly with having other objects falling to the basket and groups are a much better way of doing things.

      • vvvv

        May be.
        I thought that trying things to do via editor helps to understand things better. But now I understand that Godot has limited visual representation of object properties and its status. So I am changing the way I approach the engine. Doing things in code is the best way to keep track of everything, I believe.

    • ax xa

      Hello Dave,
      Did you solve the mouse problem?

      • ax xa

        Just to try the game short answer with the keyboard:

        extends KinematicBody2D

        func _ready():
        set_process(true)

        func _process(delta):
        var motion = Vector2()
        if (Input.is_action_pressed(“ui_left”)):
        motion += Vector2(-1,0)
        if (Input.is_action_pressed(“ui_right”)):
        motion += Vector2(1,0)
        motion = motion.normalized()*140*delta
        move(motion)

        func _on_Area2D_body_enter( body ):
        body.queue_free()

  • Radiva Hera

    hey, i have some problems here..
    my egg won’t dissapears

    • Vinod

      Inside the basket or on the ground?
      Anyway check if the signals are correctly setup and firing. This can be also the problem of the egg detection area collider inside the basket. Check that also.

      • Radiva Hera

        on the ground
        the function print(body.get_name()) is not working

      • Vinod

        Check the colliders are setup properly for both the egg and the ground, and make sure that the trigger is off in the properties

      • Radiva Hera

        oh, it works
        i forgot edit the contact monitor in the egg node
        thanks before for your help

      • Vinod

        Great.

      • Jordan

        I’m also having this problem- the egg disappears when it makes contact with the area2D in the basket, but no event is triggered when the Egg makes contact with the Ground, though the Ground does arrest the movement of the Egg. Any ideas?

      • Jordan

        Figured it out! The “Contact Monitoring” toggle was off on the RigidBody2D of my Egg. Once that was turned on, it worked fine.

      • vvvv

        I was going to ask that. Good you found the problem.

      • Vinod

        Check if contact monitor is enabled and the contacts reported to 1 for the egg node.

      • Vinod

        Check if contact monitor is enabled and the contacts reported to 1 for the egg node. I updated the post with this info.

  • Shivansh Anand

    excellent man ! God bless u always !

  • Shivansh Anand

    thanks a loty !

  • Muhammad Ali

    Well, Thanks a lot! It worked. I coulsn’t resist putting in more eggs 😀

    • Vinod

      Great

  • Muhammad Ali

    What a fantastic Series. God bless you 🙂

  • Thanks very much for the tutorial! Really appreciate them since there’s so few on Godot right now!

    • Vinod

      Glad you find it helpful.
      I am thinking of creating more tutorials.

  • Unwary

    Hello again.
    A friend and I have been teaching yourselves Godot, proceeding on from your tutorial.
    We thought we would publish our additions and so on into tutorial, continuing yours. If you have any conditions or stipulations, please let us know.
    The (somewhat ill-managed) repository is here.
    https://github.com/Norrolith/Egg-Scramble-game
    If you don’t want us to do this, then we won’t write the tutorial.
    Thank you for this great quickstart into GDscript programming,
    Unwary

    • Vinod

      No problem.

      I’d like you to mention my original post somewhere in your tutorial. Other persons can also find my pages and it may help them too.

  • Unwary

    You might want to restate the set contacts_reported note. I missed it it and it’s hard to notice once you have moved on.

    • Vinod

      OK. Will do. Thanks for your feedback.