Sites


Initiation à Godot

Adding mechanics with GDscript

Adding mechanics with GDscript

What we’ve done in the editor for now is just put together the resources that we want to use in the game and organize them. But how do we make things happen ? How does the player interact with the world ? How do I set score ? All this will need code to happen.

For this purpose Godot uses its own scripting language GDscript which takes a lot from Python. It is made to be simple to learn, readable, and is delivered with a lot of predefined classes that fasten the game development. It doen’t need compilation and is dynamically typed. Of course, this is not made to speed up rendering but make it so easy to use that it’s worth the choice. Most of the optimisation is done in the engine and GDscript gives a lot of performance improvement over Python in the game context. But for those who need more C++ can be used.

To read this chapter, it is better to have some basic knowledge of some programming concepts. You may find courses about python in our manual.

The most part of the code structure is given by Godot itself. Scripts will be attached to nodes and extends the class this node is based on. We will just need to define what is specific to the game : mostly variables and functions.

Variables

Variables are explicitely declared :

  • on top of the script file if they need to be shared through functions
  • in the function itself

Use the keyword var to declare the variable. For GDscript is dynamically typed, no need to define if it is an integer or a string or whatever. This will be done when a value is given.

 

  var speed

of course you can affect a default value at the beginning

 var speed = 100

or at any time in any function

 speed = 100

GDscript comes up with standard types (like int, float, string, bool, null, array, dictionary…) but also has some specific related to common maths calculation in a game (such as Rect2, Vector2, Vector3…) and some engine (as Color, Image, Object, InputEvent…). It is not really the purpose of this manual to describe then intensively. Get help in Godot inline reference as described below.

Note there can also been constant define with const keyword instead of var.

We sometimes export the variable in the script. This way, the variable will be displayed in the inspector. This is a good practice coders should apply for important variables. It helps non-coders and game designer to test several value and improve the game play without risking to break all the code. We’ll demo that soon.

 export var speed = 100

Functions

To declare a function you simply need to use the func keyword like this :

 func function_name() :
 function magic here
If you had a look at python, see there is no def, no self which is considered as implied. At the opposite, conditions, while or for loop are really similar.

Predefined Godot function begin with an underscore. For example the default _ready() displayed in any new script as we’ll soon see.

func _ready():
# Initialization here

Of course, as our script extends the base class, each function is a method of a class and might be called as a member.

 var player = get_node("player")
 player.do_this()

Let’s make things move with a script

Enough words and let’s see the process of adding a script.

  1. Select the root node of the scene and click the Add/Create Fode script button on top right of the panel.
  2. In the window Create Script for Node, there shouldn’t be much to change. Give a name to the script file, eventually path if you made directories for them or enable Built-in Script if you don’t want the script to be stored externally. Of course we would consider to have separate file as a better practice.
  3. The Script tab of the main view is then enable and a script template displayed. We can see the extends Node2D and a _ready() function that we’ll customize. The Inspector displays resource property like path and name.
  4. In the _ready function, delete pass and add instead  print("test"). Save the script and play the game or the scene. This will this play the game but also display the Debuggerand the output. If everything is good, «test» should appear in the Output window.
     
  5. That’s a first step, and we see everything is working, so let’s go on.
  6. In our scene, let’s add a Label Node in which we will want to display the number of passed buildings. As you may see, the label is empty. It could be set in the Inspector but let’s manipulate it with a script because at the end this will need it.
  7. Let’s create a function for it and call it score. If we want it to be used at the very beginning we need to call it in the _ready function. So we get this :

    func score():
    print("in score function") #jus add this to see if everything works

    func _ready():
    # Initialization here
    print("test")
    score()

  8. If you play, you should get both testandin score function message in the output window. If there is an error, the debugger should display it and say which script causes it and at which line (here is line 15). Here an unexpected End Of Line (EOL) caused by a missing " before the closing parenthesis.

    Click on the continue button (the only one active) to pass through and be able to close the game window and go back to your script.
  9. If you want to have more debugging message and pause the playing process to follow what’s happening, you may define breakpoints. Place the cursor on the line you want the game rendering to stop, press F9 or use Debug > Toggle breakpoints to add or remove. When playing the game, godot will stop at each breakpoint so you can see the messages or variables value. UseStep Into orStep Over buttons to go on.
  10. Let’s now change the text in the Label. First we need to access the Label Node. A really common way is to use the get_node() method. Let’s first test if node exists :

    if get_node("Label"):
       print("Label found")
    else :
       print("no label node")

  11. If a node named Label is found, the first message is displayed. Which is good. On the other way, change the label name to match your need. Finally, we need to know how to set the text in the game. If you have no idea of what to use just go to the Helptab, in the Search in Classes column, look for Label. Click on it to display all the method available for that class. On top we have a Public Methods, especially on called set_text(), which looks appropriate. Click on it to display details which say simply «set the label text». It could be worse. Let’s use it and play :

  12. if get_node("Label"):
       get_node("Label").set_text("0") 
    else :
       print("no label node")

The next thing would be to replace the text by an integer that would be incremented each time the bat passes an obstacle. Buc fist, we need to spawn buildings and the make the bat mode. Here how we did to set buildings :
 
 var obstacles = []
var spawn_ofs = 1000
export var spawn_distance = 500

func spawn_obstacle():
var obs = preload("res://pipes_random.scn").instance()
obs.set_pos(Vector2(spawn_ofs, 0))
spawn_ofs += spawn_distance add_child(obs)
printt("obstacle spawn at ", obs.get_pos())

First we declare our variable : obstacles and spawn_distance. See that we added export keyword before the second variable. This will make it displayed in the Inspector to let the game or level designer play with the value and equilibrate the game, without having to open the script file.

Then we added a function which preloads the scene containing the buildings and instantiate them. We set the position of the new instance in a Vector2 using a variable for x value. We then update values for next instance and add the instance as child of the select node.

Our function will be used as the bat will move. So that is now what we have to do.

 
Notice that the editor gives an instant syntax debugging at the bottom of the editor and changes the color of the line where an error is detected.
 

// show autoload

Il y a une erreur de communication avec le serveur Booktype. Nous ne savons pas actuellement où est le problème.

Vous devriez rafraîchir la page.