Mainloop¶
Objectives¶
In this part you learn how to write a little program for the game engine which uses a mainloop. |
Preparations¶
- Open a new blend-file
- Change the render engine from »Blender Render« to »Blender Game«
- Change to the scripting area and create the file main.py in the text editor
- Click now in the scene settings in the menu item Custom Properties on »add«
- Click on »edit« set Property Name to »__main__« and Property Value to »main.py«
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"
scene.objects["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:
time.sleep(sleep_time)
last_time = current_time
# change scene
# read keyboard input
k_events = bge.logic.KX_INPUT_ACTIVE
# uparrow key pressed
if keyboard.events[bge.events.UPARROWKEY] == k_events:
# move up cube .005 Blender-Units
cube.position[2] += .01
# downarrow key pressed
if keyboard.events[bge.events.DOWNARROWKEY] == k_events:
# move down cube .005 Blender-Units
cube.position[2] -= .01
# escape key pressed
if keyboard.events[bge.events.ESCKEY] == k_events:
# Stop mainloop -> exit program
LOOP = False
# render next frame
bge.logic.NextFrame()
You can find the keys under Blender Game Engine – events.
More about Blender and the Game Enigne under Blender Game Engine – API