π导航  


【首页】

Blender游戏引擎的Python脚本


【2020-04-12】 Blender学堂】


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.

*本教程是最新版本的Blender。如果您遇到任何错误,请在下面留下评论*


在这篇BGE Python初学者教程中,您将学习如何在Blender中使用Python脚本使汽车移动、提高速度和停止。请记住,boxcar只是用作使用Python的示例,而不是汽车物理。本教程将向您介绍Blender游戏引擎的Python脚本基础知识,包括通过脚本访问和更改逻辑块信息。在开始之前,如果您是Python新手,并且想要了解更多关于Python的一般信息,包括格式、语句、函数等等,请查看Python初学者指南。这里没有一本指南需要花很长时间来阅读,你将在一天内学会开始学习所需的一切知识。剩下的就是通过自己的项目从经验和必要性中学习。但是,即使您对Python一无所知,本教程也很容易理解。

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.

我在Blender中设置了3个窗口,左上角是3d视图,右上角是文本编辑器,底部是游戏逻辑。在本教程中,您的搅拌机应该是相同的。一旦你看到这些窗口,我们就可以开始创建我们的小游戏了。在阅读关于使用python的本教程之前,您应该已经对逻辑块的工作原理有了基本的了解,但这两种方法都很简单。逻辑块在游戏逻辑窗口中,左边有传感器,中间有控制器,右边是执行器。传感器起到触发器的作用,因此当发生按键或属性值更改等情况时,可以执行操作。控制器为您提供一组选项,用于确定如何解释或使用传感器。当满足某些参数时,执行器使事情发生。

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.

在文本编辑器中,按标题中的“新建”按钮创建新文本文件,并将其重命名为“cubeMove”。在我们写任何东西之前,我们想检查一下我们的一些视觉选项。在刚刚重命名脚本的脚本名称字段旁边有3个图标。第一个是行号。单击此按钮以启用它。这只是在每一行旁边显示数字,以便您知道要在脚本的哪一行上键入。这对于调试非常重要,因为当脚本中出现错误时,系统控制台将告诉您错误所在的行号。另外两个图标用于单词换行和语法突出显示(突出显示python关键字等,我将启用此功能)。我们需要启用的最后一件事是系统控制台。在旧版本的Blender中,这在默认情况下是可见的,但现在不再可见了。这是打印所有脚本数据和脚本错误的地方。要在Windows中启用此功能,请进入顶部窗口菜单,如果尚未显示该窗口,请选择“切换系统控制台”。有关在Linux和Mac上打开控制台的说明,请单击此处。

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.

print()是一个简单的命令,它将括号中的内容打印到控制台中,在本例中,它打印单词hello。为了让脚本真正运行并实现这一点,我们将让逻辑砖运行它。因此,在场景中选择一个对象(如果你没有像我一样制造一辆超级棒的汽车,那么默认的立方体就可以了),然后在游戏逻辑窗口中添加一个always传感器和一个python控制器。通过单击传感器旁边的小圆并将其拖动到控制器旁边的小圆来连接这两个。在python控制器的脚本字段中,键入或选择脚本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!*

现在将鼠标光标悬停在3D视图上,然后按P键。这将开始游戏。按Esc键结束游戏。检查控制台,你会看到hello这个词。你的第一个成功剧本**请注意,如果将鼠标悬停在“脚本”窗口上并按P键,则可能会在脚本中的某个位置写入P,从而导致错误。鼠标悬停在任何窗口上都是活动窗口。这个错误会经常发生,所以请记住***

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:

第一行只是导入我们需要的所有bge脚本功能,这一行应该包含在所有游戏脚本的顶部(从Blender 2.74开始)。开始游戏(鼠标悬停在3D视图上时按p键),然后查看控制台。现在,如果尚未建立连接,则dir()=目录。控制台将打印出bge模块中的所有函数,其中包含Real Time Blender的所有函数,本教程中最值得注意的是logic,其中包含我们可以用来访问逻辑块和对象属性的函数。那么,让我们打印出bge.logic的目录,看看有哪些选项。使您的脚本如下所示:

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:

因此,您应该知道,不仅可以打印bge的dir,还可以打印其所有函数的dir,例如bge.logic及其所有函数。查找控制台中列出的getCurrentController()函数。这将访问运行脚本的逻辑块控制器。一旦我们访问控制器,我们就可以访问连接到它的所有传感器和执行器,甚至可以访问有关拥有控制器的对象的信息。这是一个非常重要的功能。现在更改脚本的打印行以打印bge.logic.getCurrentController()的dir,确保它在末尾有自己的一组括号,并确保大小写正确,因为python区分大小写。因此,您的脚本应该如下所示:

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.

开始游戏并查看控制台。您将看到一组新的功能,包括执行器、传感器和所有者,它们都有自己的目录,也可以打印出来。您需要的所有信息都可以使用dir()找到。如果在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:

所以您知道打印命令和打印目录。让我们继续看一些真正的游戏脚本。删除打印行并添加两行,使脚本如下所示:

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.

看看这三行。它们几乎会在你的每一个游戏脚本的顶端,并且可能是任何blender游戏脚本最基本的三行代码。

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.

我首先解释第二行,cont=bge.logic.getCurrentController()。我之前告诉过你getCurrentController()函数的全部内容。在这里,我们只是添加了一行访问控制器并将该信息分配给变量cont。变量名可以是您喜欢的任何名称,但它通常是cont之类的缩写,我们使用它只是为了不必每次需要时都写出bge.logic.getCurrentController()。我们只是写cont。确保将括号集放在末尾。如果你不这样做,你会得到一个错误。

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.

现在转到第三行,own=cont.owner。在这里,我们访问控制器的所有者,并将该信息分配给一个变量。现在我们可以访问拥有运行脚本的python控制器的对象,在本例中是您的默认多维数据集(或我的超级跑车)。这使我们能够访问有关对象的信息,最显著的是它的游戏属性。

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.

删除always传感器并添加两个键盘传感器,一个用于向上键,另一个用于向下键。将这些传感器重命名为“向上”和“向下”。名称很重要,因为我们将在python脚本中按名称调用这些传感器。对于“向上”传感器,还应启用“轻敲”选项,以便此传感器在您按键时仅注册一次,否则在按键释放时也会注册第二次。点击可确保传感器只触发一次。将这两个传感器连接到python控制器,以便在按下其中一个按钮时运行python脚本。现在也添加一个运动执行器,并将其连接到控制器。将致动器重命名为“移动”。当按下up按钮时,我们将使用这个执行器来移动我们的汽车。


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.

查看move=cont.TRACTOR[“move”]。这将访问致动器列表中名为“移动”的致动器。如果括号中没有定义任何内容(例如:cont.acturers[]),那么所有连接到python控制器的执行器都将放入此列表中。但在这个例子中,我们只是称之为“移动”。


现在看一下“向上按”和“向下按”的行。它们访问“向上”和“向下”传感器,以便我们可以检测哪些键被按下,并使脚本对每个事件执行不同的操作。


现在查看最后一行,speed=move.dLoc[1]。在这里,我们进入移动执行器。移动执行器是一个运动执行器,我们可以使用python访问和更改不同的字段。在本例中,我们访问dLoc字段,因为这就是我们移动车辆的方式。dLoc字段实际上是X、Y和Z值的列表。我们想在Y轴上移动车辆,所以我调用dLoc列表的第二个值。如果您想知道为什么我键入[1]来调用列表中的第二个值,请注意列表项从0开始,因此调用move.dLoc[1]就是调用该列表中的第二个项。如果我想得到第一个值,X值,我会将它写为move.dLoc[0]。简而言之,通过这行代码,我们的可变速度现在将等于脚本运行时的Y值。

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:

现在我们已经声明了所有的变量,我们将添加几个语句来确定是按up键还是按down键,然后让两个键触发不同的事情。简言之,这就是我们希望发生的事情。每当播放器向上按时,运动执行器中的Y值将增加0.05,每按一次键,速度将增加更多。每当播放器按下时,Y值重置为0,使汽车停止。


我们将首先定义当我们向上按时会发生什么。因此,在速度变量下面添加行,使脚本如下所示:

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:

此if语句用于检测是否按下了up按钮。确保将内容格式化,就像我格式化一样。if语句的末尾需要一个冒号,并且该语句的任何操作部分都需要在其下方打勾。现在,如果播放器向上按,当前的速度值加0.05,该速度值插入移动执行器。dLoc是我们要更改的运动执行器中的字段。如果要更改执行器中的其他字段,要确定可用的选项,可以使用print dir(移动)。现在我们简单地插入速度变量作为列表中的Y值,它将改变执行器中的值。为了现在激活此执行器,我们使用cont.active(移动)线路。现在我们的车开得更快了。


现在我们要定义当我们按下时会发生什么。因此,添加底部的行,使脚本如下所示:

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.

Download the project files



                            

copyright©2018-2024 gotopie.com