Blender 3D News and Training

Python Scripting for the Blender Game Engine

Posted by Chris Plush on Feb 22, 2012

Learning Python!

*This tutorial is up to date with the latest version of Blender. If you come across any errors please leave a comment below.*

In this beginner’s BGE Python tutorial you’ll learn how to use Python scripting in Blender to make a car move, increase in speed, and stop. Keep in mind the boxcar is simply used as an example of working with Python, not car physics. This tutorial will teach you the basics of Python scripting for the Blender game engine, including accessing and changing logic brick information through scripting. Before getting started, if you’re new to Python and for more general information on Python including formatting, statements, functions, blah blah, check out Beginner’s Guide To Python. None of the guides here take long to go through, and you’ll learn everything you need to know to get started in a day. The rest is learning through experience and necessity through your own projects. But even if you don’t know a single thing about Python, this tutorial is easy to follow.
 
 

Setting Things Up

I have 3 windows set up in Blender, top left is the 3d View, top right is the Text Editor, and spanning the bottom is Game Logic. Your blender should look the same for this tutorial. Once you have these windows in view we can start creating our little game. You should already have a basic understanding of how logic bricks work before reading this tutorial on using python, but it’s simple enough to follow along either way. The logic bricks are in the Game Logic window, with sensors on the left, controllers in the middle, and actuators on the right. Sensors act as triggers so that when something happens such as a key being pressed or a property value changes, an action can be performed. Controllers give you a set of options that determine how sensors are interpreted or used. Actuators make things happen when certain parameters are met.
 
 

Creating a New Python Script

In the Text Editor, create a new text file by pressing the “New” button in the header, and rename it to “cubeMove”. Before we write anything we want to check out some of our visual options. There are 3 icons next to the script name field where you just renamed your script. The first is line numbers. Click on this to enable it. This simply shows you numbers next to every line so you know what line of the script you’re typing on. This is essential for debugging because when there’s an error in your script, the System Console will tell you what line number the error is on. The other two icons are for word wrap, and syntax highlighting(which highlights python key words and such, I would enable this). One last thing we need to enable is the System Console. In older versions of Blender this was visible by default, but it’s not anymore. This is where all the script data and script errors will print out. To enable this in Windows, go into the top Window menu and select “Toggle System Console” if you don’t already have that window visible. For instructions on opening the console on Linux and Mac, click here.

Now for some actual scripting. Copy and paste the code below into your new script file:

print ("hello")

print () is a simple command that prints out whatever is in the parenthesis into the console, in this case it prints the word hello. For the script to actually run and do that, we’re going to have logic bricks run it. So select an object in your scene(the default cube will do just fine if you didn’t make a super awesome car like me) and in the Game Logic window add an always sensor and a python controller. Connect these two by clicking on the little circle next to the sensor and dragging it to the little circle next to the controller. In the script field of the python controller, type in or select your script cubeMove.

Now hover the mouse cursor over the 3D View and press P. This starts the game. Press Esc to end the game. Check the console and you’ll see the word hello. Your first successful script! **Make a note that if you were hovered over the script window and pressed P, you would’ve written P somewhere in the script and it would’ve caused an error. Whatever window the mouse is hovered over is the active window. This mistake will happen a lot so keep it in mind!**
 
 

cubemove_image1

 
 

Getting Serious Now

Now erase that print line. Paste the following line at the top of your script:

import bge
print (dir(bge))

The first line just imports all the functions we’ll need for bge scripting, and this line should be included at the top of ALL of your game scripts(as of Blender 2.74). Start the game(press p while mouse is hovered over 3D View) then look at your console. Now dir() = directory if you haven’t made the connection. The console will print out all the functions in the bge module which contains all of the functions for realtime Blender, most noteably for this tutorial, logic, which contains the functions we can use to access our logic bricks and object properties. So let’s print out the directory of bge.logic and see what our options are there. Make your script look like below:

import bge
print (dir(bge.logic))

Start the game then look at your console. The console will return all the functions in the bge.logic module.
 
 


cubemove_image2

 
 

So, you should know that not only can you print out the dir of bge, but the dir of all of its functions as well such as bge.logic and all its functions too. Find the getCurrentController() function listed in the console. This accesses the logic brick controller that runs the script. Once we access the controller we can access all of the sensors and actuators connected to it, and even access information about the object that owns the controller. This is a pretty damn important function. Now change the print line of your script to print out the dir of bge.logic.getCurrentController() now, making sure it has its own set of parenthesis at the end and making sure you have the capitalization correct because python is case sensitive. So your script should look like this:

import bge
print (dir(bge.logic.getCurrentController()))

Start the game and take a look at the console. You’ll see a new set of functions, including actuators, sensors, and owner, all of which have their own directories which can be printed out too. All the information you need can be found using dir(). If you’re ever unaware of what your options are when working with objects or logic bricks in Python, you can simply print out their directory which tells you. Make note of the capitalization, and make sure all parenthesis are closed or you’ll get errors.
 
 

Scripting for Reals

So you know about the print command and printing directories. Let’s move on to some real game scripting. Erase the print line and add two lines so that your script looks like this:

import bge
cont = bge.logic.getCurrentController()
own = cont.owner

Take a look at these three lines. They’ll pretty much be at the top of every one of your game scripts and are probably the three most essential lines of code for any blender game script.

I’ll start by explaining the second line, cont = bge.logic.getCurrentController(). I told you before what the getCurrentController() function was all about. Well here we just added a line that accesses the controller and assigns that information to the variable cont. The variable name can be anything you like, but it’s typically an abbreviation like cont, and we use it simply so we don’t have to write out bge.logic.getCurrentController() every time we need it. We just write cont instead. Make sure you put the set of parenthesis at the end. You’ll get an error if you don’t.

Now onto the third line, own = cont.owner. Here we access the OWNer of the CONTroller and assign that information to a variable. Now we have access to the object that owns the python controller that runs the script, in this case your default cube(or my awesome car). This gives us access to info about the object, most notably its game properties.
 
 

Adding More Logic Bricks

Delete the always sensor and add two keyboard sensors, one for the up key, and one for the down key. Rename these sensors to “up” and “down”. The name matters because we’ll be calling these sensors by name in the python script. For the “up” sensor, also enable the “Tap” option so that this sensor only registers once when you press the key, else it also registers a second time when the key is released. Tap ensures a sensor only fires one time. Connect both of these sensors to the python controller, so that the python script runs when either of those buttons are pressed. Now add a motion actuator too and connect it to the controller. Rename the actuator to “move”. We’re going to use this actuator to move our car when the up button is pressed.
 
 


cubemove_image3

 
 
Now we’re going to add four more lines underneath own = cont.owner so we can access our new sensors and actuators in the script, and we’re creating another variable for speed. So make your script look like this by adding the bottom four lines:

import bge
cont = bge.logic.getCurrentController()
own = cont.owner
move = cont.actuators["move"]
pressup = cont.sensors["up"]
pressdown = cont.sensors["down"]
speed = move.dLoc[1]

Take a look at move = cont.actuators[“move”]. This accesses the actuator named “move” from the list of actuators. If nothing was defined within the brackets(ex: cont.actuators[]) then all actuators connected to the python controller would be put into this list. But in this instance, we’re just calling the one named “move”.

Now look at the lines for pressup and pressdown. These access the sensors “up” and “down” so we can detect which keys are pressed and make the script do something different for each event.

Now check out the last line, speed = move.dLoc[1]. Here we dive into the move actuator. The move actuator is a motion actuator and has different fields we can access and change with python. In this instance we are accessing the dLoc field because that’s how we’re moving our vehicle. The dLoc field is actually a list of X,Y and Z values. We want to move the vehicle on the Y axis so that’s why I’m calling the second value of the dLoc list. If you’re wondering why I typed [1] to call the second value in the list, make a note that list items start from 0, so calling move.dLoc[1] is calling the second item in that list. If I wanted to get the first value, the X value, I would write it as move.dLoc[0]. So in short, with this line of code our variable speed will now equal whatever the Y value is at the time the script is run.
 
 

Making Stuff Happen

Now that we’ve declared all of our variables we’re going to add a couple statements to determine if up or down is pressed, and then have both keys trigger different things. In brief, this is what we want to happen. Whenever the player presses up, 0.05 is added to the Y value in the motion actuator, increasing the speed more with each key press. Whenever the player presses down, the Y value is reset to 0, making the car stop.

We’ll start by defining what happens when we press up. So add in the lines beneath the speed variable so that your script looks like this:

import bge
cont = bge.logic.getCurrentController()
own = cont.owner
move = cont.actuators["move"]
pressup = cont.sensors["up"]
pressdown = cont.sensors["down"]
speed = move.dLoc[1]

if pressup.positive:
    speed = speed + 0.05
    move.dLoc = [0.0, speed, 0.0]
    cont.activate(move)

This if statement is used to detect whether or not the up button has been pressed. Make sure to keep things formatted just like I’ve formatted it. Your if statement needs a colon at the end of it, and any action part of this statement needs to be tabbed in beneath it. Now if the player presses up, 0.05 is added to whatever the speed value currently is, and this speed value is plugged into the move actuator. dLoc is the field in the motion actuator we want to change. If you want to change other fields in the actuator, to figure out what options are available you can use print dir(move). So now we simply plug the speed variable in as the Y value in the list there and it will change the value in the actuator. To make this actuator active now, we use the line cont.activate(move). Now our car moves faster.

Now we’re going to define what happens when we press down. So add in the lines at the bottom so your script looks like this:

import bge
cont = bge.logic.getCurrentController()
own = cont.owner
move = cont.actuators["move"]
pressup = cont.sensors["up"]
pressdown = cont.sensors["down"]
speed = move.dLoc[1]

if pressup.positive:
    speed = speed + 0.05
    move.dLoc = [0.0, speed, 0.0]
    cont.activate(move)

elif pressdown.positive:
    speed = 0
    cont.deactivate(move)
    move.dLoc = [0.0, 0.0, 0.0]

The statement elif is like saying “else if”. So if the player is pressing down instead of up, we set the speed value to 0, deactivate the move actuator which stops the car, and finally we reset the Y value in the dLoc field back to 0.
 
 


cubemove_image4

 
 

Play the game!

Your script is complete! Start the game! Now press up repeatedly to gain speed, and press the down key to stop.

We didn’t actually use the own variable in this tutorial. But as a quick example, if you created a property for your object called “health”, you would be able to read or change this value in Python by calling it like this: own[“health”].
 
 

How to debug your scripts

There may be errors in your script that prevent if from running properly. These errors appear in the system console. So if you go to play this game and nothing is working, check the system console to see what the error might be. It will even tell you the line number of the error encountered. With line numbers enabled in the Text Editor you’ll be able to find the location of the error.



Related Posts

Comments (172)

avatar
Nilesh
Nilesh

Hello, I am completely new to blender… and I am learning python for BGE…
I just want to ask you, is python necessary for creating any game in blender, or can we create any game in blender only with sensors, controllers & actuators and WITHOUT python script…?

digitalprogrammer
digitalprogrammer

Hello.
Answer: You could make easy games, like a simple plataform game. But, if the game is more sofisticaded so it will not work.
I think the most problem is the there is no file about that subject. I am tryieng to learn bge-python but is very hard the bge-API part.

Ashton
Ashton

Its possible but a little bit of a challenge. But its not as stressful when you first learn about scripting. But after you learn about scripting its easy.

Bob Hope
Bob Hope

Python error compiling script – object ‘Cube’, controller ‘And’:
File “cubeMove”, line 4
move = cont.actuators[“move”]

Syntax Error: invalid character in identifier

Chris Plush

Fixed, you can copy and paste from the tutorial without any problems now.

Chris Plush

I thought I fixed this problem before but looks like it popped up again for some reason. The issue here is the quotation marks. When you copy and paste from a web page into blender the quotation marks are different than the ones needed for python. So try backspacing all the quotations marks in your blender script and typing in your own quotation marks in their place. This will solve that issue. I’ll work on getting that problem fixed in the tutorial today thanks for letting me know.

Braňo Rachmad Mrkva Rabatin
Braňo Rachmad Mrkva Rabatin
I wanted to make a suspension with 6 degrees of freedom constraint, that worked in Blender 2.4*, for example this: http://www.tutorialsforblender3d.com/GameModule/ClassKX_PyConstraintBinding_1f.html (or just google BGE Vehicle wrapper which was some sort of package containing working car suspension with a small bug that the car tilted to a wrong side when reversing). Unfortunately I get the error: name ‘GameLogic’ is not defined. In what state is vehicle wrapper which worked some years ago? Namely, it relies heavily on this PhysicsConstraints module but I can’t get those old scripts to work. Do you plan to make a tutorial for a car suspension… Read more »
Braňo Rachmad Mrkva Rabatin
Braňo Rachmad Mrkva Rabatin

I managed to do this 6DOF constraint, but the instruction “setParam” (where we set type of spring and it’s stiffness parameter) is not recognized by Python/Blender. It would be very useful to have some kind of library “where’d that syntax go?” so I can reimplement older scripts into newer versions of Blender…

Chris Plush

For people like me that don’t really play with python for a couple years at a time I suffer a bit of relearning each time haha. I haven’t really kept up with things so I’m not sure where the setParam has gone sorry. These days I just make sure my basic python tutorials are kept functional and up to date.

Flavio Remy Frottin
Flavio Remy Frottin

Nice Tutorial,very good.

how can limit this acceleration ?

for example 0 to 2

Chris Plush

You would use the line: if pressup.positive and speed < 2:

That statement would only allow the speed variable to increase if its less than 2. You can find out more about conditions like that here: https://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements

Flavio Remy Frottin
Flavio Remy Frottin

I solved in this mode:
if speed >= 2:
move.dLoc = [2,0,0]

Thank you for link

Igor Vasilyev
Igor Vasilyev

I have a character – http://joxi.ru/KAxeW4jcW7qgr8

I press “gun” – action from logic begin – he step forward and shoot.

I wish when I press “gun” again – next his step starting from new position – http://joxi.ru/KAxeW4jcW7qgr8

just remember this new position after step.

do you know how to do this?

Chris Plush

To do that you’ll need to make sure the armature has a location animation moving it forward that plays at the same time as the walking animation. Then you just simply need to enable “Add” and “L”(local movement) on the action actuator for the location animation. Here’s an example blend file showing the animation playing from whatever location the cube is at:

https://www.cgmasters.net/resources/using_actions_to_move_object.blend

Igor Vasilyev
Igor Vasilyev

Chris, thank you very much for demonstate this.

I solved this slightly different way http://blenderartists.org/forum/showthread.php?387126-NEED-HELP-BGE-and-buttons-for-animation-remaining-location&p=2975543&viewfull=1#post2975543

But with complicate animation , it’s look no good. for example legs move constantly (when leg on the floor it’s move with location animation)

wpDiscuz