您的位置:首页 > 编程语言 > Python开发

Python Scripting for the Game Engine

2013-11-08 17:12 429 查看
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:

import bge


This line will be at the top of pretty much all of your game scripts. The bge module contains all of the Python functions
for realtime Blender, so it’s necessary to import this module so we can access all of its functions to use in our scripts. Add in another line below that, which makes better use of the print command, so that your script looks like this:

import bge
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, 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 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.getCurrentContr
10baf
oller() now,
making sure it has its own set of parenthesis at the end, so that the script looks 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, printing directories, and you know about import bge. 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.



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 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:

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.



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)
- See more at: http://www.cgmasters.net/free-tutorials/python-scripting/#sthash.v7nHNHzi.dpuf
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: