Make Games with Godot 4 and AI · Lesson 3 of 11

GDScript Tutorial: Variables, Functions & _process (Godot 4 Lesson 3)

Time to write some code. You'll learn GDScript variables, functions, and if statements while making the character move left and right with the arrow keys and making the coins gently bob up and down.

In this lesson, we'll bring the screen you built in Lesson 2 to life. When you're done, the ← → arrow keys will move the character left and right, and the coins will gently bob up and down.

Finished project for Lesson 3: project-lesson03.zip (5 KB)

If something isn't working, compare your project with this one. Extract the zip, click "Import" in the Project Manager, and select project.godot to open it.

Attach a script

In Godot, you give a node behavior by attaching a script to it. Scripts are written in GDScript, Godot's own language. It's similar to Python and easy to read.

  1. Open main.tscn, right-click Player in the Scene dock, and choose "Attach Script".
  2. In the dialog, check that Language is GDScript, Inherits is Sprite2D, and Path is res://player.gd. You can leave Template as Node: Default.
  3. Click "Create", and the main screen switches to the script editor.

The new script already has a few lines in it. Delete them all and type in the code below. Copying and pasting is fine, but typing it yourself at least once helps it stick.

player.gd
extends Sprite2D

# Movement speed (pixels per second) that you can change in the Inspector
@export var speed: float = 300.0

# The player's name (just a regular variable)
var player_name: String = "Hopper"


# Called once, when the node enters the scene
func _ready() -> void:
	print(make_greeting(player_name))


# Called every frame. delta is the time in seconds since the previous frame
func _process(delta: float) -> void:
	var direction: float = 0.0
	if Input.is_action_pressed("ui_left"):
		direction -= 1.0
	if Input.is_action_pressed("ui_right"):
		direction += 1.0

	position.x += direction * speed * delta

	# Keep x between the left and right edges so we stay on screen
	var screen_width: float = get_viewport_rect().size.x
	position.x = clamp(position.x, 64.0, screen_width - 64.0)


# Takes a name and returns a greeting message
func make_greeting(who: String) -> String:
	return "Hi, " + who + "! Your speed is " + str(speed) + "."

Save with Ctrl + S and run with F5. If the character moves when you press ← →, it works. From here, we'll go through this code piece by piece, from the top.

player.gd open in Godot's script editor, with line numbers and color-coded code
player.gd open in the script editor
Indent with Tab

GDScript uses the indentation at the start of each line to show which lines belong together as a block. In Godot's script editor, you indent with the Tab key. If the indentation gets messed up when you copy code from a web page, delete the spaces at the start of that line and press Tab again.

Line 1: extends

extends Sprite2D declares "this script builds on everything Sprite2D can do." That's why, inside this script, you can use things Sprite2D already has, like position, directly. It's the same Position you saw in the Inspector.

Variables and types

A variable is a labeled box that holds a value. You create one with var.

Variable examples
var score: int = 0
var speed: float = 300.0
var player_name: String = "Hopper"
var is_alive: bool = true
var lives := 3   # With :=, the type is inferred from the value on the right (int here)

The : int part is the type, a promise that "this box only holds whole numbers." When you write types, Godot warns you before the game even runs if you put the wrong kind of value in.

TypeWhat it holdsExamples
intWhole numbers0, 3, -10
floatDecimal numbers300.0, 0.5
StringText"Hopper"
boolYes/notrue, false
Vector2A pair of numbers (x and y)Vector2(576, 480)

Variables created outside of functions (near the top of the file) stick around for as long as the node exists. Variables created inside a function (like direction in _process) disappear when that function finishes.

Functions

A function is a named chunk of code. You create one with func. Let's look at make_greeting at the very bottom.

func make_greeting(who: String) -> String:
	return "Hi, " + who + "! Your speed is " + str(speed) + "."
  • (who: String) is a parameter: a value the function receives from whoever calls it.
  • -> String is the return type. This function returns text. A function that returns nothing is written as -> void.
  • return sends a value back.
  • str(speed) is a function that turns a number into text. You can't join text and a number directly with +, so you need to convert it (see Common errors).

You call a function by writing its name followed by (), like make_greeting(player_name).

_ready and print

Functions whose names start with _ (an underscore), like _ready and _process, are functions Godot calls for you automatically at specific times. You don't need to call them yourself.

_ready is called only once, when the node has entered the scene and is ready. It's where you put setup code.

print() shows text in the "Output" panel at the bottom of the editor. When you run the game, you should see this in the Output panel:

Output
Hi, Hopper! Your speed is 300.0.

print() doesn't show anything on the game screen. It's a tool for developers to check "what's in this variable right now." When something goes wrong, looking at values with print() is the first step in debugging.

_process and delta

_process(delta) is called every frame. A game redraws the screen dozens of times per second, and each of those redraws is a frame. Anything that moves goes here.

The delta parameter holds how many seconds have passed since the previous frame. On a computer that redraws 60 times per second, that's about 0.0167 seconds.

position.x += direction * speed * delta

This line means "increase the x position by direction × speed × elapsed time." speed is 300, so if you hold the right arrow key, the character moves 300 pixels per second.

If you left off * delta and wrote something like position.x += direction * 5, it would mean "5 pixels per frame." Written that way, the character moves faster on a faster setup (like a monitor that redraws 144 times per second). Multiplying by delta keeps the speed the same on every computer.

if statements and keyboard input

	var direction: float = 0.0
	if Input.is_action_pressed("ui_left"):
		direction -= 1.0
	if Input.is_action_pressed("ui_right"):
		direction += 1.0

if condition: means "run the indented lines below only when the condition is true."

Input.is_action_pressed("ui_left") returns true or false depending on whether a button for the ui_left action is being pressed right now. ui_left and ui_right are actions built into Godot, mapped to the ← → arrow keys and a gamepad's D-pad.

If only left is pressed, direction is -1; if only right, it's 1; if both are pressed, they cancel out to 0; and if nothing is pressed, it's 0. We multiply this direction by the speed to move.

When you have several conditions, use elif (otherwise, if...) and else (if none of the above).

if / elif / else example
if score >= 100:
	print("Amazing!")
elif score >= 50:
	print("Nice!")
else:
	print("Keep going!")

Keeping the character on screen

	var screen_width: float = get_viewport_rect().size.x
	position.x = clamp(position.x, 64.0, screen_width - 64.0)

get_viewport_rect().size.x gets the screen width (1152), and clamp(value, min, max) keeps the x position between 64 and the screen width minus 64. 64 is half the width of the character image (128 × 128).

Tweak values in the Inspector with @export

@export var speed: float = 300.0

Putting @export in front of a variable makes it show up in the Inspector. Select Player in the Scene dock, and you should see Speed at the top of the Inspector.

Set Speed to 600 and run the game, and the character moves twice as fast. You can try out values without editing the script, which makes finding "just the right speed" much easier. Values you change in the Inspector are saved in the scene and take priority over the 300.0 written in the script.

There's a lot more you can do with @export. For details, see The complete guide to @export annotations in Godot 4.

Make the coins float

Now for the coins. Open coin.tscn, attach a script res://coin.gd to the root node Coin using the same steps, and write the following:

coin.gd
extends Sprite2D

# How far (in pixels) and how fast the coin bobs
@export var float_height: float = 8.0
@export var float_speed: float = 3.0

var time: float = 0.0
var start_y: float = 0.0


func _ready() -> void:
	start_y = position.y


func _process(delta: float) -> void:
	time += delta
	# sin() glides smoothly between -1 and 1, which makes the coin bob up and down
	position.y = start_y + sin(time * float_speed) * float_height
  • In _ready, we remember the coin's starting y position in start_y.
  • In _process, we keep adding to the elapsed time time and use sin() to make a wave between −1 and 1. Multiplying it by float_height (8) makes the coin sway up to 8 pixels above and below where it started.

Save, go back to main, and run it with F5. Because you attached the script to the coin scene, all three coins in main move. This is what Lesson 2 meant by "fix the block, and every copy updates."

The running game. The character has moved to the right, and the coins are slightly offset up and down
The right arrow key moves the character, and each coin bobs up and down
Try it
  • Select just Coin2 and set Float Speed to 6 in the Inspector. Only that one coin bobs faster.
  • How would you make the coins sway side to side too? Try adding start_x and using cos() on position.x.

Bonus: arrays and for loops

We don't use these in the game yet, but they come up a lot in later lessons, so here's a quick introduction. An array is a list of values in order, and a for loop repeats code.

Array and for loop example
var fruits: Array[String] = ["apple", "orange", "grape"]
for fruit: String in fruits:
	print(fruit)   # Prints apple, orange, grape in order

for i in 3:
	print(i)       # Prints 0, 1, 2 (3 is not included)

To try it out, put it inside _ready in player.gd.

Common errors

When there's a mistake in your script, an error appears in red below the script editor, and the line gets marked. Here are the ones beginners run into most, along with the actual messages Godot 4.6 shows.

Error messageCause and fix
Invalid operands "String" and "float" for "+" operator.You're trying to join text and a number with +. Convert the number to text, like str(speed).
Unexpected "Indent" in class body.Usually this means a missing colon : at the end of the line above. Without the :, as in func _ready() -> void, the indentation on the next line is reported as "unexpected." Check the line above, not just the line with the error.
Used space character for indentation instead of tab as used before in the file.The indentation mixes tabs and spaces. Delete that line's indentation and re-indent with Tab.
Function "Print()" not found in base self.Wrong capitalization. GDScript is case-sensitive, so it's print, not Print.

Error messages can look intimidating, but give them a read. They tell you which line has the problem and what happened. If you're still stuck, pasting the message as is into an AI and asking about it works well too.

Working with AI

If you hand this lesson's work to AI

Writing code is what AI does best. But while you're learning, we recommend asking it to explain rather than asking it to write.

This is GDScript for Godot 4.7. Read player.gd and explain it line by line for a beginner. In particular, explain in detail why we multiply by delta. Don't change the code.
Update coin.gd so the coins slowly sway side to side as well as up and down. Make the new variables @export so I can tweak them in the Inspector.
  • A (chat): paste in the error message and your code, and it will usually find the cause. Be sure to say "Godot 4," or you may get answers written the Godot 3 way (like export var).
  • B (Claude Code, etc.): it reads and writes player.gd directly. But the AI can't see whether the edited code actually moves the character when you press the right arrow key. You run it with F5 to check, and if something's off you report back, like "Pressing the right arrow key doesn't move it." That's the back-and-forth.
  • C (+ MCP): the AI can run this back-and-forth loop on its own. With Godot MCP Pro, for example, the AI checks the script for syntax errors (validate_script), runs the game (play_scene), holds the right arrow key for 0.5 seconds (simulate_key), takes a screenshot (get_game_screenshot), and confirms the character moved before reporting "Done."

Whichever approach you use, you still run it yourself at the end to check. Even when the AI says "Done," you're the one who decides whether it feels good and does what you wanted.

Recap and what's next

  • Scripts are attached to nodes. extends builds on the original node's features
  • Create variables with var name: Type = value. Types include int / float / String / bool / Vector2
  • Create functions with func. You can also write parameter and return types
  • _ready is called once at the start; _process(delta) is called every frame
  • Multiplying movement by delta keeps the speed the same on every computer
  • @export lets you tweak values in the Inspector
  • A missing colon shows up as an error on the next line

Right now the character is a Sprite2D, so it's just an image moving around; it can't bump into floors or walls. Next time, we'll define our own controls with the InputMap, rebuild the character as a CharacterBody2D, and get ready for jumping.

Want AI to run the "write → run → check" loop for you?

With Godot MCP Pro, Claude Code or Cursor can run the code it writes, send key presses, and check how things move with screenshots (190 tools, $15 one-time purchase). You can finish this series without MCP.

Learn more about Godot MCP Pro · How to let AI playtest your game

All lessons in the series (11)
  1. Lesson 1: Installing Godot and setting up AI tools
  2. Lesson 2: Nodes and scenes
  3. Lesson 3: GDScript basicsYou are here
  4. Lesson 4: Input and player movement
  5. Lesson 5: Gravity, jumping, and tilemaps
  6. Lesson 6: Signals, coins, and enemies
  7. Lesson 7: UI and screen transitions
  8. Lesson 8: Sound and game feel
  9. Lesson 9: Letting AI playtest your game
  10. Lesson 10: Exporting and publishing
  11. Lesson 11: Bonus: one-prompt games by genre