Python Scripting for the Game Engine

Posted by Chris Plush on February 22nd, 2012 | Comments (144)

Learning Python!

In this beginner’s BGE Python tutorial you’ll learn how to use Python scripting in Blender 2.6 to make a car move, increase in speed, and stop. 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.

Click here to download the blend file. This file is the finished product and is not necessary to download in order to do the tutorial. All models and textures packed in the blend file are yours to do with what you will.

 

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 Help 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!**

 

Getting serious now

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

print (dir(bge))

Start the game(press p while mouse is hovered over 3D View) then look at your console. 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:

print (dir(bge.logic))

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

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:

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:

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.

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:

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 value because that’s how we’re moving our vehicle. We want to move the vehicle on the Y axis so that’s why I’m calling the second value of the dLoc field. 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:

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:

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.

 

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 error with no problem.

-Chris (blengine)

 

  • http://Website nick

    this is awesome, thanks

    • http://Website Anshul

      hiii…
      Very nice tutorial.Can u tell me how can i move my man character with the help of script like ur game.
      can u tell me the script or any tutorial based on scripting(which can move my character)
      Thanks. :)

    • http://Website anshul

      hi..
      i ma using this script on my character which have armature bt it doesnt work.
      i had add an action actuators ant also add a walk action on the script.can u tel the script…?????????

      • http://www.cgmasters.net Chris Plush

        This script works when applied to an armature too, it just has to have all the same logic bricks(and have all logic bricks named the same way: up, down, move). I don’t know any advanced scripts for character motion but you may have luck searching through http://www.blenderartists.org

  • http://Website Aniruddha Hardikar

    Thank you so much!! I was looking for a starting point for BGE scripting, and this seems to be perfect!

    • http://Website anshul

      hiii Aniruddh.
      can u help me in scripting???????from where u blong in india..?????????

  • http://Website Allan

    Wow! Even the code ‘reads like a book’. Thanks so much.

  • http://Website arun

    thanks . i want the car should move reverse .. plz help me

    • http://www.cgmasters.net Chris Plush

      You can simply subtract 0.05 from speed instead of adding 0.05 to it. That way the value will be negative and make the car go in reverse.

  • http://Website andries

    Wow very informative and well explained!

  • Pingback: Python Scripting for the Game Engine | BlenderNation

  • http://Website Habanita

    Thanks for this great introduction !! Can’t wait for more !!!!!!!

  • http://blendersushi.blogspot.com Jimmy Gunawan

    Cool intro, it’s making us wanting for more!

    Sometimes I think it is a good idea also to show “what if” you were to do this manually.

  • http://Website bob

    why is it that even if i set the dLoc to 0 or 2, it still moves it on the y axis?

    • http://www.cgmasters.net Chris Plush

      If you’re still changing the Y value in the dLoc field its going to keep moving on the Y axis. If you set it to 0 though it should have stopped. If you’re still having trouble you could paste your script so I could take a look.

      • http://Website bob

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

        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]

        Here it is.

        Thanks for helping.

      • http://www.cgmasters.net Chris Plush

        Ah, when you plugged speed into the dLoc value you still have it as the Y value.. You need to change that line to move.dLoc = [speed, 0.0, 0.0], so that speed is plugged in first(for the x value).

    • http://Website crankyjoe

      I think it has to do with where you put the speed variable in your move.dLoc line ie;

      if pressup.positive
      speed=speed +0.05
      move.dLoc = [0.0, speed, 0.0]
      if you see this as move.dLoc = [ X, Y, Z, ] then you will realize that is where you would change to directional component.
      To move the cube along the X axis the code would look something like move.dLoc = [speed, 0.0, 0.0]

      make sense?

      i think.

  • http://Website bob

    Oh I get it thanks a lot man your the best.

  • http://Website sculptorjim

    Just to add my thanks for a great tutorial. I hope you move on soon to more complex things.

    Any reference material on GameLogic module would be a really useful addition.

  • http://Website Tom

    Great Tutorial. One Question: Is there a way that my cube gains speed while holding a key instead of tapping it?

    • http://www.cgmasters.net Chris Plush

      At the top left of the up-key sensor there’s two buttons with triple quotes on them. The one on the left is called True Pulse Mode, and when this is enabled the sensor will trigger constantly when the up key is held in. You can even change how frequently the sensor is triggered by enabling True Pulse Mode then increasing the Frequency value next to it.

  • http://Website shadow

    I had lots of trouble with this tut. since I was using mac I ahd to open the console diferently. also gamelogic does not import. but bge does. has it been changed since this tut?

    • http://www.cgmasters.net Chris Plush

      I’m updating the tutorial tonight to use bge.logic and describing how to find the console on a mac. Thanks for letting me know about these things. GameLogic still works for me in 2.63 on windows but bge is more current.

  • http://www.cgmasters.net Chris Plush

    just updated the tutorial using bge.logic and added a link for instructions on opening the console in linux and mac

  • http://www.t-maschine.de togy

    great tutorial, i was searching for something like this for getting started. would be great if you could make somemore great stuff like that. =)

  • http://Website Thomas H. Culhane

    Chris, this is the most helpful and well written tutorial I’ve yet seen and I will be using it with students around the world. Thanks for also posting your awesome car and racing environment and for taking the time to answer everyone’s questions. Your hard work is much appreciated! We look forward to more of your tutorials!

    • http://www.cgmasters.net Chris Plush

      Thanks Thomas! That’s an amazing thing to hear, I appreciate it and am really glad you found this useful. If you have any suggestions for more tutorials let me know.

  • http://Website Michael Wenas

    Chris, I’m very interesting. This is a great tutorial. But, I want to ask something. Is there a way that the cube will move when I press a key and stop when I release that key? Thank you

    • http://www.cgmasters.net Chris Plush

      Yes sir there is a way. Delete the down-key sensor, enable true pulse on the up-key sensor, and make your script look like the script below. With true pulse enabled, the script will run as long as the up key is pressed in. And when it’s released the script will stop running and the values will be reset.

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

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

      else:
      speed = 0
      cont.deactivate(move)
      move.dLoc = [0.0, 0.0, 0.0]

      • http://www.cgmasters.net Chris Plush

        make sure you tab the right lines in, the tabbed lines didn’t appear correctly in the reply

      • http://Website Michael Wenas

        Thanks. That’s very helpful. I look forward for another tutorial. Great job

      • http://none Rafael Assis

        Hi Guys, I’ve tried this script, but tried to add some more so I could move my character front and backwards.

        But I did not get it to work perfectly, i’ve tried as this:

        import bge
        cont = bge.logic.getCurrentController()
        own = cont.owner
        motion = cont.actuators["move"]

        downkey = cont.sensors["down"]
        pressup = cont.sensors["up"]
        speed = motion.dLoc[0]

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

        if downkey.positive:
        speed = speed – 0.05
        motion.dLoc = [0.0, speed, 0.0]
        cont.activate(motion)

        else:
        speed = 0
        cont.deactivate(motion)
        motion.dLoc = [0.0, 0.0, 0.0]

        once you add the downkey sensor, the pressup stops working, it only works when you add each sensor to a different script. Which is not that bad, but it is lame of me to not make it work in one script!
        Any suggestions?

        thanks!

        ps. Ive tried with elif for the downkey also, but with no success!

      • http://none Rafael Assis – SOLVED

        Problem solved! Turns out i did not realize that

        I was setting two “elses” for the same movement, one for up key and one for down key and both got were active at the same time and both stoping movement!

        The solution was just remove the else for up key, turn the down key to a else if and the magic is done!

        Thanks!

        here the updated code for moving foward and backwards:
        Character will move only when keys remain pressed and stop upon key release.

        import bge
        cont = bge.logic.getCurrentController()
        own = cont.owner
        motion = cont.actuators["move"]

        downkey = cont.sensors["down"]
        pressup = cont.sensors["up"]
        speed = motion.dLoc[0]

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

        elif downkey.positive:
        speed = speed – 0.05
        motion.dLoc = [0.0, speed, 0.0]
        cont.activate(motion)

        else:
        speed = 0
        cont.deactivate(motion)
        motion.dLoc = [0.0, 0.0, 0.0]

  • http://Website Drew

    I typed in the code correctly, but when i hit p to start the game and i hit up arrow, nothing happens.

    • http://Website Drew

      Nevermind. My apologies :P I did make an error in the code haha

  • http://Website Bill

    Thanks for the wonderful explanation of exactly how this all works together! It’s just what I needed to wrap my brain around it all. I had some pieces of information from various tutorials and user manual, but none of them showed how it all works together on a basic level like you show here. Great job!

  • http://Website Drew

    What is the name for left click in the text editor? Im making a minigun and I want to hole left mouse button down to make it spool up. Is there a way?

    • http://Website Drew

      hold*

      • http://www.cgmasters.net Chris Plush

        Hey Drew, download this example file to find out how that’s done, http://www.cgmasters.net/resources/minigun.blend

        In short, when you left click it adds value to a property and this property value is used to the spin the barrel. When the barrel reaches a certain speed it triggers a firing actuator.

  • http://Website Drew

    Thanks Chris!

  • http://Website Olev

    Any hardcore tutorials or examples where multiple objects getting data from server or something like that :D ?

    • http://www.cgmasters.net Chris Plush

      That’s not a topic I can cover, but I’m looking for some python gurus to join the site and cover really advanced topics like that, so in the future we’ll definitely have tutorials like that.

  • http://Website Mr Z

    I both downloaded the .blend file and also created my own file using this guide though I am unable to “print(dir())” anything. In console all I get is Blender Game Engine started and finished. Nothing in between. Same thing happens if I try to print “hello” for instance, nothing shows up. I am using Blender 2.63. What am I dping wrong?

    • http://www.cgmasters.net Chris Plush

      Are you pressing the up or down keys when you start the game? The script is only run when the sensors connected to it are triggered.

      • http://Website Mr Z

        Yes! If I run the script through the downloadable blend it all works great! The problem is I can’t print the directory of bge, which is what I want to do. Thanks for reply!

      • http://www.cgmasters.net Chris Plush

        Can you copy and paste the script you’re using here so I can just double check it?

      • http://Website Mr Z

        Sure!

        import bge
        print(dir(bge))

        The only thing I get printed out in the console is “Blender Game Engine has started” and “Blender Game Engine has finished”. Though if I try print(“Hello”) for instance, that works!

      • http://www.cgmasters.net Chris Plush

        That’s really strange, that should work. Does print (dir(bge.logic)) work for you?

      • http://Website Mr Z

        No, nothing prints out it does not matter what I try to print wether it is print(dir(bge)) or print(dir(bge.logic)) or even print(“Hello”).

      • http://www.cgmasters.net Chris Plush

        I have no idea what’s wrong, maybe is a python version issue. Try this:

        print “hello”

        That’s how it used to be formatted, but now print is a function. You should’ve gotten an error though if that’s the case, but this is all I can think of.

        • http://N/A David

          I was having the same problem as Mr.Z printing the word, hello. I am running 2.63a out of Desperation I typed in print (‘hello’) and that solved the issue. I hope this helps someone.

  • http://Website Vincent Peluso

    Hey Chris, just wanted to thank you for this excellent beginner python bge tutorial. It is extremely helpful for a beginner python user such as myself.

    Secondly, I have the same problem as Mr Z. I can’t get the dir function to work at all. I even copied and pasted the exact 2 lines of code you used:

    import bge
    print (dir(bge))

    I’m using blender version 2.63a on a windows 7 PC and i see that you used that version as well to do this, so I’m just lost as to why it won’t work. Any help will be appreciated. Thanks

    • http://Website Vincent Peluso

      Also forgot to add that all i get in the Console window is “Blender Game Engine has started” and “Blender Game Engine has finished”, just as Mr Z does.

  • http://Website Sprite

    I downloaded your completed file, and toggled the system console, but I still go the error: “no module named bge” I have blender v.2.62 . Also when I pressed “p” on the workspace it just switched to textured view mode. However when I presse alt+”p” on text editor it did the same thing as the run script button.

    • http://www.cgmasters.net Chris Plush

      Try the latest version of blender and see if that gets rid of the “no module named bge” error”. This was made with 263 so maybe the python changes that were made recently happened between versions. The only reason I can think of that the p key would enable texture view is if you changed your keyboard configuration. But you can play the game from the menus by changing the “Blender Render” option to “Blender Game” in the very top header, and then going to the Game menu and selecting Start Game Engine. Check the keyboard config too to see if that hotkey was changed.

      • http://Website Sprite

        Thanks for replying, Chris. I haven’t changed my keyboard configurations, so its probably something I did wrong because I misunderstood something along the way. I was set at blender render and reset it to blender game mode, but that didn’t change anything noticeable. I will try downloading the newest version of Blender, do you happen to know if its out in portable yet, because I haven’t found anything new on that yet.

  • http://Website Sprite

    I downloaded v.2.6.3 and got all the same results as before.

    • http://www.cgmasters.net Chris Plush

      Ah, are you running the script from the game, or by pressing alt+p? Alt+p is not for game scripts, and it will cause that error. Game scripts must be run from within the game by a python controller. So start the game and press up or down to run the script.

  • http://Website Sprite

    Wow. That worked. That was a lot simpler than I thought. Thanks. But why would it give me those errors when I pressed alt+p or “run script”? It doesn’t make sense to me. Also, when I toggle the console open, it is completely blank, with nothing written in it.

    • http://www.cgmasters.net Chris Plush

      You can create regular scripts for blender that you run with alt+p, like if you create scripts to aid in modeling or animation. Game scripts need to be run while the game is running. From what I understand the game engine is essentially a separate part of blender, just integrated in it, so game scripts need to be run by the game engine. Is the console blank after you run the game and/or try the print () function?

  • http://Website Sprite

    Thanks for explaining that to me. The console is blank before I run the game and after, even if I use the print() function. It doesn’t even list any information I suspected it would on start up about the blender or python. Entirely blank.

    • http://www.cgmasters.net Chris Plush

      I don’t know why that’s happening without peaking over your shoulder. You could try running blender from the command prompt(start menu > run > cmd.exe, then type in the path to the blender.exe file)

  • http://Website Sprite

    I gave up with the console because even that wasn’t working for me (I’m sure I just didn’t type it in right) I’m going to use this that I found instead: http://www.blendernation.com/2010/07/21/blender-python-bindings-for-notepad/

  • http://Website james

    Sprite, I was having the same problem for a little while. Double check just to make sure an “always” actuator is attached to your script and that the python script is pointing to the proper text file.

  • http://Website Sprite

    Yup, I got the script running fine, thanks for replying James. I found out though, that the console worked on another computer with same software same running program, while it didn’t still on the other computer I was using. After a bit of research on the subject, I have also seen no one have a similar problem to mine.

  • http://Website smartie

    scripts dont look impossible anymore safe

  • http://Website need a help

    will i get game engine in blender 2.64 itself ?thanks.

    • http://www.cgmasters.net Chris Plush

      Yep, the game engine is in Blender, including all the latest versions.

  • http://Website Ginger26

    hi , awesome tutorial on bge and python . I wana know if you can make a tutorial like this but with a car thats fully controlable , like wheels turning and having all the behaviour of a real car . I really wana make a racing game with blender . Such a tutorial will be perfect thanks

    • http://www.cgmasters.net Chris Plush

      It won’t be any time soon but that would be a good topic for a future tutorial, thanks!

  • http://code.google.com/p/pywingui maxim

    Blender is very good! But what is if I want create simple 3d game with 15 minutes? Now you can try Game Builder based on pyWinGUI and pyIrrlicht.

  • http://Website vaibhav

    on running:

    import bge
    print (dir(bge.logic))

    I am getting the following error-”import bge
    print (dir(bge.logic))”

    i am using blender 2.65

    • http://www.cgmasters.net Chris Plush

      vaibhav, I’m not getting any errors with that code in 2.65. What’s the actual error say when it happens?

  • http://Website Crankyjoe

    I great tutorial. easy to understand and not a video. too many of those lately (imho)

    Now to my problem:
    I followed the tut exactly yet, it wouldn’t play. I literally cut and pasted the text of the script from the tut and got the exact same error. So, so long as your syntax is good (and I’m not doubting that it is) then my Syntax is good. My error in the console shows:
    KeyError: ‘requested item “move” does not exist’ and has a traceback to line 4 which is the declaration of the move variable. I’m kinda stumped here. got anything? thanks

    • http://Website Crankyjoe

      update: The sample blend worked fine on my machine (with the exact same script.) this is leading me to believe there must be something wrong with the setup of my logic blocks but I looked them over and they are the same too,,,

      …im stumped.

  • http://Website Crankyjoe

    ok, I am officially a moron LOL. I never changed the name of the actuator from “motion” to “move”

    works fine now,

    thanks again…sorry for all the needless posts.

    • http://www.cgmasters.net Chris Plush

      haha, no problem, glad you figured it out! And I totally agree about video tutorials. I personally don’t care for them, but most people seem to love them. I’ll be doing more text tutorials in the future though, especially when it’s data related like python tutorials.

  • http://Website sheetal

    Its really helpfull……………..thanks

  • http://Website paul

    that was a great tut, I was wondering if you could explain getting the attribute list for the edit object actuator, i need to control the linear velocity but dont know the attribute name. I really like what you are doing and hope you can help me, Thx Paul

    • http://www.cgmasters.net Chris Plush

      Hey Paul, name your Edit Object actuator “act1″ or something like that, then connect it to a python controller and a sensor to trigger it. Then use the following script. It’s the same as I use above to get the directory for bge, only instead of printing dir(bge) I’m printing dir(act1).

      import bge
      cont = bge.logic.getCurrentController()
      act1 = cont.actuators["act1"]
      print (dir(act1))

  • http://Website Tochukwu Bedford

    Honestly, this tutori@l w@s indeed very helpful. Now I’ve got @ b@sic underst@nding of python.

  • http://n/a mike kelly

    i know its been out awhile but i just finished that bow and arrow tut cant believe i got it to work . nice . thank for makin it

  • http://Website benicourt

    Good introduction, thank you, ready for the next !

  • http://Website Gin

    get tutorial. I can seem to get objects to show textures in the Viewport Shading selection. I am using Blender 2.68a. Can you tell me how you were able to get your objects to show textures? Thanks!

    • http://www.cgmasters.net Chris Plush

      To enable GLSL shading for the viewport, press the N key to open the right-side toolbar in the 3d View, scroll down to the Display panel, and change the view type to GLSL. If your graphics card supports it then you’ll be able to see your materials/textures in the 3D View. Press alt+z to switch to textured view afterward.

      • http://Website Gin

        Thanks so much. Another question about textures – if i change the texture on the banner to something else, it shows when rendered. But in textured mode it still shows the original checkered texture.

        • http://www.cgmasters.net Chris Plush

          With GLSL enabled textured view should show exactly what the render shows. If you have another display type enabled like mulittexture or singletexture then the objects in the 3d view will display the images they are uvmapped to. So if the banner is still uvmapped to the checker image, that will be shown in textured view. Simply go into edit mode, select all and change the image its uvmapped to.

  • http://Website Verde

    Hello! One question, if I want to rotate my cube (around each exis) how I shoul proceed?
    Thanks?

    • http://www.cgmasters.net Chris Plush

      Hey Verde, you would use dRot instead of dLoc

  • http://yanzicjustubie.wordpress.com zeeco

    Blender bpy module can be loaded to external python IDE,
    how about bge,
    it is posible to load bge module to external editor/IDE ?

  • http://Website pang_tom

    I set speed = move.dLoc[0] or speed = move.dLoc[1] or speed = move.dLoc[2] car can move but I think when I set move.dLoc[0] or move.dLoc[2] car must stop
    please explain to me

    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]

    Thank you very much… :)

  • http://Website Friv ric

    If there just would be flash version of that game, I’d happily post it to my site.

  • http://Website Carter

    I just go straight up instead of on the y or x axis

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

    if pressup.positive:
    speed = speed + .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]

    • http://www.cgmasters.net Chris Plush

      The vaues in the dLoc field represent X, Y, and Z. Try changing the value of a different axis in that field to go in a different direction. Your car object may have a different orientation than the car object I used for this tutorial.

  • http://Website Daniel RIdge

    For some reason, the Console won’t print anything out for me, not even a simple.
    print (“Hello World”)

    I have absolutely no idea what is wrong, I’ve even uninstalled and reinstalled blender to try to fix it.

    • http://www.cgmasters.net Chris Plush

      Hey Daniel, it sounds like the script isn’t running. Did you make sure to set up the logic bricks to run the script when the game plays? If you’re still having trouble, upload your blend file for me or you can even email it to me as well at contact@cgmasters.net and I’ll check it out.

  • http://Website Brendon McDonough

    Hello Chris; thanks for the wonderful starter kit to scripting.

    I have been able to adapt the script quite successfully to a flight control model I am developing, using dynamic control instead of static movement, using force and torque values instead of location changes but one hiccup I have encountered is the need to repeatedly press a key to continually add to the value, rather than it adding while the key is held down and returning it to a default value when released.

    what part of the script is nullifying the input until the input key is pressed again?

    will continue trying but I am sure others would like the same functionality.

    • http://Website Brendon McDonough

      I think I have figured it out.

      because the key assignment uses if statements, the script only runs once per keystroke. Not only that, if multiple keystrokes are listed, (mine has up, down, pan left, pan right), pressing multiple keys results in the action of the last key pressed, rather than a combining of the two states.

      for the time being, I will run a separate script for each input key sensor brick, rather than multiple bricks running to one script.

      if there is a way of containing it all in one script I would love to know.

  • http://Website Name

    how to limit the movement of the car does not exceed a certain value?

    • http://www.cgmasters.net Chris Plush

      Limit the speed you mean? The modified script line would then read:

      if pressup.positive and speed < 1:

      So as long as the speed value is less than 1 the car can continue to increase in speed.

  • http://none Nice

    Hi I am using Blender 2.70 and I need a car model. Can you create a tutorial that shows how create a simple car please?

    • http://www.cgmasters.net Chris Plush

      Hi, in our DVD section we have a course available on creating a 2012 Camaro ZL1. We don’t have any other car modeling tutorials planned for any time soon, but at some point in the future we’ll probably be making more cars, see ya!

  • http://Website Name

    Also Blender 2.70 will not let me import BGE nor anything that has to do with game engine. Anyway to solve this?

    • http://www.cgmasters.net Chris Plush

      I just tested this script and blend on blender 2.70a, and it works fine. Can you tell me what error you’re getting in the console? And you’re running the script by running it in the game engine correct? Trying to run this script like a regular blender script by pressing alt+p over the script window will result in errors.

  • http://none Cool

    Well when I do “import bge” the console gives me an error say “‘No ‘moudle’ named ‘bge’”. Is bge already built-in and don’t need to be imported?

    Also I made a tank and I want to make its wheels rotate making the tank move. Does this tutorial actual do that? I never animated actual 3d stuff like bullets that come out of the barrel you know.

    • http://www.cgmasters.net Chris Plush

      You need to run the script using a python controller logic brick so it runs in the game. If you try running it outside of a game by pressing “run script” you’ll get that error. Go through this tutorial to understand how using a game script works. It’s also possible you might get that error if you’re using a special build that does not include the game engine, so make sure you’re using the official blender 2.70a release from blender.org. And no this tutorial has nothing to do with wheels rotating or bullets firing.

    • http://www.cgmasters.net Chris Plush

      Oh, I noticed something that may be causing the error. Scripting is case sensitive. So writing import BGE will give you that module error, because bge must be in lower case, so make sure it’s written like this:

      import bge

      • http://none Cool

        I tried import bge it don’t work. Maybe it is built-in and don’t need to be imported.

        • http://www.cgmasters.net Chris Plush

          Ah you’re right, it looks like 2.70a doesn’t need import bge, however it still shouldn’t return an error. Well figuring that out doesn’t matter, just leave it out and if everything works then problem solved.

        • http://none Cool

          So don’t need to call bge in anything that is in this code you made?:

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

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

          else:
          speed = 0
          cont.deactivate(move)
          move.dLoc = [0.0, 0.0, 0.0]
          - See more at: http://www.cgmasters.net/free-tutorials/python-scripting/?replytocom=213325#respond

          Or do I still have to do bge.logic or bge.blablabla?

        • http://www.cgmasters.net Chris Plush

          Everything else is necessary, you just don’t need import bge at the top. It imports bge by default but you still need to call the functions by specifying which module they’re from.

  • http://none Cool

    Your stuff is not working for my model car. followed your whole tutorial and nothing seems to work. Not even your code. I figured an easier way of doing this though. I just create functions that were already created for me and others in blender.

    But I wanted to use your code so can you fix this?

    • http://www.cgmasters.net Chris Plush

      Upload or email your blend file with the code in it to me. You can email me at cjplush@gmail.com. I’ll take a look at it and try to figure out what’s going on.

  • http://none Cool

    I want give my email but you can go to my onedrive: https://onedrive.live.com/?cid=93930F70EF15C00C&id=93930F70EF15C00C!107

    You can try to run my blend files and test your scripts there. If you don’t receive that error this would be kinda odd.

    • http://www.cgmasters.net Chris Plush

      I need the actual blend you’ve tried the script on, with the script set up and everything so I can figure out exactly what’s wrong.

  • http://Website Abbas

    i have Blender 2.7 and my blender have not (“bge”) folder in modules folder.
    when i copy top code and press ALT+P to run script i give this error:
    name ‘bge’ is not defined
    plz help me. What i should to do?

    • http://www.cgmasters.net Chris Plush

      Hey Abbas, ALT+P is for regular blender scripts, not BGE scripts. BGE scripts must be run in-game through a python controller logic brick. This tutorial shows you how to do that.

  • http://Website Gary

    hi chris i was wondering if there is a statement to add to stop the car after reversing.

    I got the script to go forward, added a speed limt and a reverse, but the car continues to move backwards slowly or until i press forward.

    also if i was to create a track with corners how would i get the car to follow,

    • http://www.cgmasters.net Chris Plush

      Hey Gary, this tutorial isn’t exactly for car movements, I just used a car as an example for accessing logic bricks. You probably wouldn’t use scripting for basic car movements, but regular logic bricks using the Force fields in the Motion actuator. The Force fields are only visible in that actuator when your object is set to Dynamic in the Physics properties(make sure Blender Game is enabled in the top header for dynamic option to appear in the physics properties). Force basically applies an impulse to the car instead of changing it’s location like dLoc. I would use logic bricks to turn the car as well. Car controls are not something I’ve experiment much with so I couldn’t really walk you through the details to perfect the movments. But maybe I’ll look into that this year and make some tutorials on it.

  • http://Website Rudi Ratlos

    How can I set the car at a certain location? For example by pressing the spacebar, the car should go to its original position.

    • http://www.cgmasters.net Chris Plush

      Hey Rudi, add a keyboard sensor and rename the sensor to “space” without quotes, input spacebar for the key, and connect it to the same python controller as the other sensors. Then add the following to the script:

      space = cont.sensors["space"]
      if space.positive:
          own.worldPosition = [0,0,0]
          move.dLoc = [0.0, 0.0, 0.0]
          cont.deactivate(move)

      This says if the spacebar sensor activates then move the car to position 0,0,0 in the world, or whatever position you specify. It also sets the speed back to 0 and deactivates the movement actuator to stop the car.

  • http://Website Rudi Ratlos

    Thank you so much for your quick answer. Could you recommend a link, where I can find such orders like worldPosition and so forth. I looked around a lot before asking you and could not find anything suitable. Most I found were things concerning bpy…, and these orders obviously dont work within bge.

    • http://www.cgmasters.net Chris Plush

      You can find all the available options for anything using the dir() function. For example, to see all the available options for your object like worldPosition, you would create this script and run it in game:

      cont = bge.logic.getCurrentController()
      own = cont.owner
      print (dir(own))

      The dir() function returns a directory of available functions and attributes for whatever is specified in parenthesis, in this case we print out the directory for the owner, or the object that owns the python controller that runs the script. Hope that helps!

      • http://Website Rudi Ratlos

        It helps at least a bit. Is there any possibility to get it as a list? Tthat would be better readable.
        If you ever publish a new tutorial, please let me know. This one (including all comments and your answers) was very useful, the best one that I have found since I began to learn Python by trial and error.

        • http://www.cgmasters.net Chris Plush

          It prints in the console as a list. There’s no explanation of what each option does if that’s what you’re looking for, but many of them are self explanatory. Like orientation is rotation, position is location, and so on. And thanks for the kind words! I actually released 2 other python tutorials recently, check the tutorials page, and follow us on facebook for updates on more tutorials. I’m going to be making a lot more python tutorials soon. https://www.facebook.com/cgmasters

        • http://Website Rudi Ratlos

          This link seems to be very useful for me.
          Thank you once again!

  • Blender Nova

    Hi, thanks for the tutorial. I was just wondering how you can edit properties within the script? Also how you can move something to a certain position, as in dLoc moves something from where it was, wheres i need it to jump to the exact location of another object. Thanks

    • http://www.cgmasters.net/ Chris Plush

      Let’s say our object has a game property called health. This can be read using the line: own["health"]. In the script you can change this value like this:

      own["health"] = 5

      To find the object location in the world you can use own.worldPosition, which gives you a list of XYZ coordinates. To set its location you would use the line:

      own.worldPosition = [0, 0, 0]

      The three values in brackets represent the x, y, and z axis.

      • Blender Nova

        Thank you for your reply, it all works well, however has sparked a new question, how do i find the location of the object at every frame. So for an example, as i move the cube it is updated live to know the exact location of the cube, so then later i can move another object to the cubes location.

        • Blender Nova

          Actually don’t worry :) I figured it out, i was looking at the other tutorial, about the angle and so on, and i did some tweaking and figured it out.

          Loc = own.localPosition

          That one line :)
          Anyway thanks

        • http://www.cgmasters.net/ Chris Plush

          You can do that a couple ways. You can have any object run that script and it’ll tell you its location. Or you can actually call that object into the current script even if it’s not the one running it. Here’s how. Let’s assume the other object’s name is “Cube”, you can use this line to get its location:

          cube_loc = bge.logic.getCurrentScene().objects["Cube"].worldPosition

          This line gets the Cube object from a list of objects in the current scene and returns its world position. Also, localPosition and worldPosition are very different. World position gives you the exact position in the world the object is located, regardless of any other factors like parenting. Local position is calculated based on the distance that object itself moved. So for example, if Cube was parented to another object and you moved the parent object, the Cube’s localPosition will NOT change since it’s not the object that moved, but worldPosition would show it’s actual location despite that.

        • Blender Nova

          Thanks for the reply, it all worked, and thanks for the detailed description of local position and world position.

        • Blender Nova

          Hi, me again haha, just had another question, this one isn’t needed seriously, I was just interested if you could get the name of the current object running the script,

          so say: House_Roof ran the script, it would get the name, House_Roof, and then be able to use that in your example before:

          cube_loc = bge.logic.getCurrentScene().objects[" (Puts new name here) "].worldPosition

          Then would the script be able to run for more than one object?

        • http://www.cgmasters.net/ Chris Plush

          Hmm, I’m not entirely sure what you’re trying to do with all of that, but you can get the name of the current object running the script by using the “own” variable. “Own” is actually the current object running the script.

  • ######

    how can we make a dead effect

    • http://www.cgmasters.net/ Chris Plush

      There are many ways to die, all of which will give you the effect of being dead. I’m assuming this is a blender related question though, so can you be more specific about what you’re looking for?

  • Pingback: michael

  • Pingback: francis

  • Pingback: marvin

  • Pingback: Patrick

  • Pingback: Shannon

  • Pingback: tyrone

  • Pingback: lance