a In this part you learn how to write a little program for the game engine which uses a mainloop.


  1. Copy the example
  2. Add keys and functions


  1. Open a new blend-file
  2. Change the render engine from »Blender Render« to »Blender Game«
  3. Change to the scripting area and create the file in the text editor
  4. Click now in the scene settings in the menu item Custom Properties on »add«
  1. Click on »edit« set Property Name to »__main__« and Property Value to »«

The script

First import the module of the Blender Game Engine, bge.

import bge
ATTENTION:You can’t run the script with Run Script now, because the module bge can only be imported, if the Game Enigne is active. You can start the program now by clicking »P« while the cursor is over the »3D-View«.
#! bpy
import bge
import time
import timeit

# active scene cube
scene = bge.logic.getCurrentScene()
# the object "Cube"

keyboard = bge.logic.keyboard

LOOP = True
FPS = 60  # Frames per Second
last_time = timeit.default_timer()

while LOOP:
    # mainloop
    # wait until next frame
    current_time = timeit.default_timer()
    # sleep time until next frame
    sleep_time = 1 / FPS - (current_time - last_time)
    if sleep_time > 0:
    last_time = current_time

    # change scene
    # read keyboard input
    k_events = bge.logic.KX_INPUT_ACTIVE
    # uparrow key pressed
    if[] == k_events:
        # move up cube .005 Blender-Units
        cube.position[2] += .01
    # downarrow key pressed
    if[] == k_events:
        # move down cube .005 Blender-Units
        cube.position[2] -= .01
    # escape key pressed
    if[] == k_events:
        # Stop mainloop -> exit program
        LOOP = False
    # render next frame

You can find the keys under Blender Game Engine – events.

More about Blender and the Game Enigne under Blender Game Engine – API