Skip to content

Scripting Guide

S.U.P.E edited this page Nov 6, 2026 · 1 revision

Scripting Guide

Game logic in Heaven3D lives in Blueprints: small Python classes you attach to scene objects. This page walks you through writing them. Every class and method is listed on Scripting API Reference.

Where scripts live

Put .py files in your project's scripts/ folder:

My Game/
├── main.heaven3d
└── scripts/
    ├── coins.py
    └── doors.py
  • Every .py file in scripts/ is imported automatically when the editor or the game starts, in name order.
  • Files whose names start with _ are skipped (use them for helpers you import yourself).
  • scripts/ and the project folder are put on sys.path, so scripts can import each other.
  • Errors are printed to the console with a traceback; the engine keeps running.

Your first blueprint

# scripts/spinner.py
import glm
from Heaven3D import Blueprint, blueprint

@blueprint
class Spinner(Blueprint):
    def on_begin_play(self):
        self.properties.setdefault("speed", 90.0)   # editable in the Inspector

    def on_tick(self, dt):
        self.node.rotation_euler.y += float(self.properties["speed"]) * dt   # degrees per second

⚠️ Always put @blueprint above the class. It registers the class by name, which is how the level file restores it on load. A blueprint that isn't registered is skipped with a warning ("not registered; not restored").

Attach it in the editor (the blueprint list in the Inspector) or from code:

engine.attach_blueprint(node, Spinner)
engine.attach_blueprint(node, Spinner, {"speed": 180})

A node can carry several blueprints (for example EnemyAI + Health). node.blueprint is the first one; node.blueprints is the list.

The lifecycle

Hook When
on_begin_play(self) once, when Play starts (or immediately if attached during play)
on_tick(self, dt) every frame while playing; dt = seconds since the last frame
on_message(self, event, data) when any code calls send_message (or a targeted variant)
on_collision_enter(self, other, contact) this object started touching something solid
on_collision_stay(self, other, contact) still touching (every physics step)
on_collision_exit(self, other) stopped touching
on_trigger_enter(self, other) / on_trigger_exit(self, other) something entered / left this trigger
on_end_play(self) Stop was pressed (put things back here)

When you press Stop in the editor, every object returns to its saved transform, but your own state (variables you set) is up to you — reset it in on_end_play.

What a blueprint can reach

self.node the object: .position, .rotation_euler, .scale, .visible, .material, .collider, .rigidbody, .children, .name, .tag
self.engine the running HeavenEngine
self.properties a dict saved with the level and shown in the Inspector
self.log(msg) print to the console with the class name

Common engine calls:

e = self.engine
e.audio.play("pickup")                               # 13 built-in sounds or your own files
e.hud.text(0.03, 0.05, "Score: 10", size=28)         # call every frame
player = e.first_blueprint("FPSController")          # find the player
e.send_message("coin_collected", {"value": 1})       # tell every blueprint
if e.input.was_key_pressed("e"): ...                 # keyboard
hit = e.raycast(origin, direction, 50.0)             # physics query
e.schedule(2.0, self.explode)                        # call later
e.destroy_node(self.node)                            # remove safely
e.save_game("slot1", {"coins": 7})                   # persistent data

Talking between objects: messages

Messages decouple your objects. Anyone can broadcast; every blueprint gets on_message.

@blueprint
class Coin(Blueprint):
    def on_tick(self, dt):
        player = self.engine.first_blueprint("FPSController")
        if player and glm.distance(player.node.position, self.node.position) < 1.5:
            self.node.visible = False
            self.engine.send_message("coin_collected")

@blueprint
class Score(Blueprint):
    def on_begin_play(self):
        self.coins = 0
    def on_message(self, event, data):
        if event == "coin_collected":
            self.coins += 1
    def on_tick(self, dt):
        self.engine.hud.text(0.03, 0.04, f"Coins: {self.coins}", size=32)

Built-in blueprints already speak a few messages — send damage to hurt anything with Health, listen for died, etc. The full list is on Scripting API Reference.

To target just one object (or its parents / children) use message_node, message_ancestors and message_subtree.

Detecting the player

Two reliable patterns:

  1. Distance check in on_tick (what the Coin Collector template does). Simple and robust.
  2. Trigger collider: set self.node.collider.is_trigger = True and implement on_trigger_enter(self, other). To check whether other is the player, compare against the node that carries FPSController.

Spawning and destroying

prefab = self.engine.find_node("EnemyPrefab")       # an invisible template object
clone = self.engine.instantiate(prefab, position=glm.vec3(0, 1, 5))
self.engine.schedule(10.0, self.engine.destroy_node, clone)

instantiate copies meshes, materials, colliders, rigid bodies and blueprints. destroy_node is deferred until after all ticks, so it's safe to call from collisions and messages.

Save games

best = self.engine.load_game("best", default={}).get("seconds")
self.engine.save_game("best", {"seconds": 42.5})

Data must be JSON-serialisable. Saves are atomic and backed up; see Portable Projects and Save Games.

Finding project files

path = self.engine.asset_path("assets/music/theme.ogg")   # works after the project is moved or exported
self.engine.audio.play_music(path)

A complete example: the Coin Collector

Create a project from the Coin Collector template and open scripts/coins.py. It contains:

  • Coin — spins and bobs, is collected by distance, plays a sound, broadcasts coin_collected, and restores itself in on_end_play.
  • CoinCounter — counts coins, runs a 60-second timer, draws the HUD, shows YOU WIN! / TIME'S UP!, and keeps the best time with save_game.

Try these changes: make coins spin faster (120 * dt), raise TIME_LIMIT to 90, or play "jump" when a coin is collected.

Writing a standalone game in Python

You don't have to use the editor at all:

import glm
from Heaven3D import HeavenEngine, SceneNode, FPSController, Weapon

eng = HeavenEngine(mode="runtime")

ground = eng.add_cube(size=1.0, name="Ground")   # solid by default
ground.scale = glm.vec3(50, 1, 50)               # collider scales with the node

player = SceneNode("player", parent=eng.scene.root)
player.position = glm.vec3(0, 1, 0)
eng.attach_blueprint(player, FPSController)
eng.attach_blueprint(player, Weapon)

eng._begin_play()
eng.run()

Tips

  • Use self.properties.setdefault(...) for values you want tweakable in the Inspector; they're saved with the level.
  • Don't hold on to nodes across Stop/Play in module-level globals — look them up again in on_begin_play.
  • Heavy per-frame work? Do it every few frames, or use engine.schedule.
  • Packages can register blueprints too, and those work in exported games. See Writing Packages.

Clone this wiki locally