Blender Python Scripting



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. Tags: Python, addon, Scripting, visual, spring21, nodes Built by Blenderheads, for the Blender Community The Blender Market's goal is to give our community a trusted platform for earning a living with software that we all love, Blender.

Learning Python!

Python Scripting Blender has a very powerful yet often overlooked feature. It exhibits an internal full fledged Python interpreter. This allows any user to add functionalities by writing a Python script. Python is an interpreted, interactive, object-oriented programming language. Focusing on Pipeline and Data Flow as well as research and development. Main tools I used here were Python, Maya and Houdini. Worked at Prompto on the Pipeline and Data Flow. Focusing on Unreal and Blender tools / automation. All done with Python. Besides CGI, I have a strong love for backend web development, AI, automation and programming in. Blender has an internal text editor to write scripts on Python language. However, this editor is much inferior to specially designed for writing code IDEs. There is no satisfactory autocomplete, comfortable syntax lighting, possibility to organize projects in Blender internal text editor – all those things that determine the speed and ease of.

*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

Scripts For Blender

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 () 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!**

Getting Serious Now

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

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:

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

Blender Python Scripting Animation


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:

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.

Python

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:

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. Graph for mac. 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. Gta for mac dmg.


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:

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:

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:

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.


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.