Pygame Studio
PTDownload
Download

Scripts and Behavior

How to write an object's behavior in Python: the Behavior class, export fields and the per-frame lifecycle.

A script is a .py file in the project with a class that inherits from Behavior. The class is attached to an object in the scene, and that object is available as self.node.

from pgstudio import Behavior, KinematicBody, Vec2, export


class Player(Behavior[KinematicBody]):
    speed: float = export(240.0, min=0)

    def on_update(self, dt: float) -> None:
        move = Vec2(self.input.axis("left", "right") * self.speed, 0)
        self.node.move_and_slide(move, dt)

Behavior[KinematicBody] tells the editor the type of self.node, so autocomplete suggests move_and_slide, on_floor and the rest. Without the argument, class Player(Behavior) types self.node as Node2D.

Attach a script to an object

Right-click the object in Explorer and choose Attach script, or use the Attach script button on the ribbon’s Code tab. The file is created in scripts/ and opened in the code editor.

Exported fields

A field marked with export(...) shows up in the object’s Properties panel, and the chosen value is saved in the scene:

speed: float = export(240.0, min=0)

The first argument is the default value. The others (like min) describe the field to the editor. The editor reads these fields by looking at the code, without running it.

Lifecycle

Method When it runs
on_ready() Once, when the game starts or the scene changes. Parents before children.
on_update(dt) Every frame, with dt in seconds.
on_draw(surface) Every frame, after drawing, with the pygame surface so you can draw on top.
on_input(event) For every pygame event (keyboard, mouse…).

Each frame runs in this order: input, on_update, physics, camera and drawing (sorted by layer, z and tree position), with the UI on top.

What a script can see

  • self.node: the object the script is attached to.
  • self.scene: the scene, with find, tween, change_scene and set_volume.
  • self.input: the input map, with pressed, held, released and axis.

The full list of members is in the Scripting API.

Run and reload

The game runs in a separate process: if it crashes, the editor stays up, and Stop only ends that process without touching the scene you are editing. When a script raises an error, the game pauses and the error shows in Output with the file and line. When you save the script, hot reload reloads the module and the game carries on.