In this part of the Catch the ball game series, we will create the basket to catch the egg. In the previous post, we setup the physics for the egg and the ground. In the current state, the egg will drop down and sit on the floor.
Create the basket
Our basket has to be physics enabled and also it has to be controlled by the player. So we use KinematicBody2D.
Click on the ‘main’ node, then add a KinematicBody2D node as its child. Rename it to ‘basket’. Then add a sprite node as its child and set its texture as basket.png. Then click on the ‘basket’ node again and add a ‘CollisionPolygon2D’.
Select the CollisionPolygon2D node and you can see a pencil icon on the top of the editor.
Click on the pencil icon and draw the collision shape like this.
Move the position of the ‘basket’ and place it below the egg on the ground. You can click on the lock icon on the top to lock a node, so that it won’t move accidently. Now click play and you can see the egg drops, collides perfectly with the basket. Because the basket is a KinematicBody, it won’t repel or rotate by responding to the egg hit.
When the ball drops down inside the basket, we have to remove the egg. For that we need to check if the egg dropped inside. So add an Area2D node as a child of the ‘basket’. Add a CollisionShape2D and set the shape as a circle.
Setting up the collision detection
Add a script to the ‘basket’ node.
If we just add the line
_ready() function, when we run the game, we can see the output tab showing the output “test”. This means everything is working perfect.
Now we are going the editor way of binding the signals. So click on the Area2D node and click on the ‘Edit Node Connections’ button on the top.
Clicking the button will open signal list for the selected Area2D node.
In the list, choose body_enter option. Click on the Connect button. This ‘body_enter’ signal detects when a body is entered in the area collision shape. Now, we see this window.
We have a script attached on the basket node, so choose the basket node. Make sure the Create function option is turned ON. Then click ‘Connect’.
Now our basket script is populated with the callback function. Then click on the egg node, then on the properties panel, enable Contact Monitor and change the Contacts Reported to 1. If this is not set, the collision will work but the callback won’t work. Test it by adding a print statement inside the function.
func _on_Area2D_body_enter( body ):
We can see the output panel shows this,
Let us conclude this part and in the next part we will spawn the egg randomly.
[Total: 3 Average: 3.3/5]