Книга: Mastering Blender
Назад: Part V: Mastering the Blender Game Engine
Дальше: Chapter 16: Python Power in the Blender Game Engine

Chapter 15

Making Things Happen in the Game Engine

Now that you’ve created a character and a simple environment for use in the game engine, the next thing you need to know is how to add user interactivity. The Blender Game Engine (BGE) has several ways in which interactivity can be programmed into a game environment. In this chapter, you will learn about Blender’s built-in game design tools: logic bricks.

Logic bricks have the advantage of using Blender’s built-in graphical user interface to implement interactive functionality. For nonprogrammers, this affords an easy way to get started with game creation without needing to know any programming. For greater scalability and versatility, Python can also be used, which is the topic of Chapter 16, “Python Power in the Blender Game Engine.” Using Python in the game engine also relies on logic bricks to a certain extent, so regardless of how you ultimately want to program your Blender games, you will need to be familiar with the logic brick system.

In this chapter, you will learn to

Working with Logic Bricks

Logic bricks are the BGE’s way of controlling how user input controls in-game events and how those events in turn control other events. Using logic bricks, you can make a character respond to your keyboard input, trigger a level change when a certain number of points are collected, and even set up some basic artificial intelligence (AI) behavior for your character’s enemies.

In this chapter, you’ll also read about working with rigged characters, properties, and other functionality specific to interactive content and game creation. Only the very basics of working with rigid bodies and game physics are touched on here. If you are interested in setting up more-sophisticated rigid body interactions or in using BGE rigid body behaviors in your Blender animations, I recommend that you refer to Chapter 8, “Bullet Physics and the Blender Game Engine,” for more information on those topics.

The idea behind logic bricks is simple. Logic bricks enable you to associate cause-and-effect relationships and action-reaction behaviors with objects in the game environment. In this chapter, you’ll learn how to work with logical relationships that are built into the BGE logic bricks system. In Chapter 16 you’ll learn how to expand the logic to include Python scripts, leading to countless new possibilities for game design.

Understanding Logic Brick Basics

As mentioned previously, the logic brick system enables units of logic to be associated with 3D objects. Every logic brick is associated with a single 3D object. Logic bricks may affect more than one object’s behavior, however, and they may “communicate” with each other (as you will see later in the “Using Properties, Messages, and States” section). For this reason, there is not always a fixed, “correct” way to set up game logic. When you get a sense of how logic bricks work, you will develop intuitions about which objects should have which logic bricks associated with them.

After you have placed your character in the scene, you need to add user controls to enable the player to move the character around that scene. Because both the motion of the character and the defined actions can be controlled through the armature, the sensible way to set up these logic bricks is to associate them with the character’s Armature object.

Before starting on game work, be sure to select Blender Game from the Render Engine drop-down menu in the Info header at the top of your work area.

To get started with logic bricks, enter the Logic Editor window by selecting the joystick icon from the Editor Type menu, as shown in . Then select the Armature object in your scene (in Object mode), and you will see the panels shown in .

Selecting the Logic window type

c15f001.tif

Logic properties area

c15f002.tif

The leftmost portion of this panel is where you'll deal with setting properties later on in this chapter.

The remaining portion of the Logic buttons area is devoted to the logic bricks proper. Logic bricks fall into three distinct types, which are organized in columns from left to right. The logic brick types are as follows:

Sensors The logic bricks in the leftmost column are sensors. Sensor logic bricks handle the cause side of the game logic. Sensors are defined to look for specific triggers for events.
Controllers The middle column is where the controllers reside. Controllers connect sensors to actuators. Although in the simplest cases they may initially seem superfluous, controllers are the heart of the BGE game logic. They behave as Boolean logic gates with multiple sensor inputs. In cases where Python scripts are used in the BGE, the scripts themselves take on the role of controllers.
Actuators The logic bricks on the right are actuators. Actuators are the logic bricks that make things happen as a result of the sensors connected with them.

Making the Character Walk

To set up the basic walking motion of the character, you’ll use all three of these logic brick types. To do this, follow these steps:

1. In the Sensors column, add a new sensor to the Armature object by selecting the Armature in Object Mode in the 3D viewport, then clicking the Add Sensor menu beside the Armature tag in the Logic Editor. This tag appears in the area only if the Armature object is selected in the 3D window. When you do this, you will see the choices available for sensor types. Choose Keyboard here, as shown in . The Keyboard sensor brick is shown in . The text field to the right of the drop-down menu is where you can give the logic brick a name. This can be helpful to keep things orderly, but the name is optional and arbitrary.

Adding a sensor to the Armature object

c15f003.tif

A Keyboard sensor

c15f004.tif
2. Click the light gray button next to the word Key so that it displays the message “Press A Key.” The next key you press will be entered in this Keyboard sensor. Press the up arrow on your keyboard, and Up Arrow appears, as shown in .

Up Arrow selected in the Keyboard sensor

c15f005.tif
3. In the Controllers column, add a controller in the same way you added a sensor previously, by choosing And from the Add Controller menu. The And controller means that if multiple sensors are connected to the left side of the controller, the actuator on the right will be triggered only when all of the sensor criteria are met. Connect the sensor logic brick to the new controller brick by holding down the left mouse button and dragging your mouse from the small circle on the right of the sensor brick (the outlet) to the small circle on the left of the controller (the inlet), as shown in . This connection can be severed by holding Ctrl and the left mouse button and dragging your mouse across the connecting line, as though cutting it with a knife.
4. To complete this logical circuit, add an actuator to the Actuators column. In this case, you’ll start by making the armature walk according to the walk cycle set up in Chapter 14, “Creating Assets for the Blender Game Engine,” so select Action from the Add Actuator drop-down menu, as shown in . Recall that the walk cycle action you created in Chapter 14 was called Walk, and it cycled from frame 1 to frame 20. Enter the name of the action in the Action field and the start and end frame numbers in the Start Frame and End Frame fields, respectively.

Adding a controller

c15f006.tif

Adding an Action actuator

c15f007.tif
5. Select Loop Stop from the play mode drop-down menu below the Action field. This determines how the action will be played when the actuator is triggered. The play mode will play the action once. Loop End will loop the action as long as the actuator remains triggered, and when the actuator is released, the action will continue to play until its end frame. Loop Stop will discontinue the action midway through as soon as the actuator is released. This is the most natural setting for a walk cycle in this situation. The settings for the Action actuator are shown in .

Settings for the Walk Action actuator

c15f008.tif
6. Connect the actuator to the controller in the same way you connected the sensor to the controller. If you enter the BGE game play mode now with the P key, you will find that pressing the up-arrow key on your keyboard will activate the walk cycle. This is the first step to getting your character to be fully controllable.
7. At present, the character is going through the motions of walking, but it’s not moving anywhere. To make the character move, you need to add a Motion actuator, as shown in . If your armature’s axes are the same as mine, the forward movement for the armature is in the negative Y direction. On the Motion actuator, the three columns of values represent x-, y-, and z-axes in that order, so to make the object move along the y-axis negatively, put a negative value in the middle Loc field. A value of –0.05 will yield an appropriate speed. The L button you see to the right of those values ensures that the local coordinates are used, so it should be selected.

A Motion actuator

c15f009.tif
8. To give the character the ability to turn right, add a sensor for the right arrow on the keyboard and connect it via a new controller to another Action actuator identical to the previous one, and add a Motion actuator with a negative Rot value around the local z-axis, as shown in . Do the same to make the character turn left with the left-arrow key and walk backward with the down-arrow key.

Logic bricks for turning right

c15f010.tif

If you press P now, you should find that your character now is able to walk around the scene. However, the vertical placement of the character does not change, so it may seem that your character is walking on air, and furthermore walls and obstacles do not put up any resistance. To remedy this, you must enable some dynamic properties on your character.

Adding Dynamics to the Character

Game physics settings are found in the Physics properties area, in the same place that physics settings for fluid, smoke, and collision were found in Part II of this book. However, for setting game physics, the render engine must be set to Blender Game. If you haven’t set the render engine in this way, a different set of physics options will be available.

When you add an object to a scene, it is automatically created with certain basic physical properties, because the Physics button is pressed by default. This mimics the behavior of earlier Blender versions that did not have the capability to completely disable all physics effects. In this default state, an object will not move or be influenced by forces such as gravity; however, the object will act as an obstacle for other physical objects. With the Physics button deselected, there will be no interaction between the object and other objects; physical objects will pass through this object as though it is not there.

When Physics is selected, you then have the option to make the object an actor, which means that forces and interaction will be calculated with respect to this object and its surroundings. Dynamic objects are able to move in response to forces on them. If Actor is selected, the object is visible by the “near” and “radar” detection methods. The Ghost option prevents the object from being an obstacle and enables other objects to pass through it without resistance. These options are not mutually exclusive. The Ghost option is different from having no physics applied at all because it allows for the possibility that the Ghost object could also be dynamic, whereas no dynamic behavior is possible if Physics is fully disabled.

If the object is set to be dynamic, then other parameters related to its mass and collision boundaries also can be set. Finally, if the object is dynamic, it becomes possible to set the object as a Rigid Body object. This means that not only will it move in space in response to directional forces, but it will also have a full complement of angular rigid body forces calculated, resulting in a much more realistic tumbling and bouncing motion. In the case of rigid body simulation, the type of collision boundary selected also will have a considerable impact on the behavior of the object. You can read more about this in Chapter 8.

In the present case, rigid body dynamics are not necessary for the character. The character should settle on the floor and treat walls as obstacles, but for the present game the character doesn’t need to be able to tumble and roll around (which would make it difficult to control with the simple walking motion you’ve set up so far). For this reason, it is enough to make the character dynamic only, without rigid body physics. To set this up, follow these steps:

1. Because the character’s mesh is parented to the armature, it is enough to ensure that the armature behaves dynamically. Select the Armature object in Object mode and make it an actor by clicking the Actor check box in the Physics buttons panel. Also click Dynamic, as shown in .
You can leave the other values as they are for the moment. This is all that’s needed to make the armature dynamic. With the mesh armature-parented to the armature, the mesh’s own Physics settings will be disregarded in the game engine environment. To keep things uncluttered, you can disable these settings entirely, as shown in .

Making the armature dynamic

c15f011.tif

Disabling Physics on the mesh

c15f012.tif
2. If you press P now and enter Play mode, you should see the character drop down onto the floor. However, as you can see in , the character is presently dropping down too far into the floor. The reason for this is that the armature’s collision boundary is too small.
If you look at the character in Wireframe view in Object mode, you will see the collision boundary radius shown as a dotted line, as in . Armatures have only one option for collision boundary shapes; they are always spherical, and the bounds are set by the Radius parameter.
Another way to see what’s happening here is to use the Show Physics Visualization option available in the Game drop-down menu, as shown in . With this activated, you will see all physical boundaries explicitly drawn in the game-play environment, as shown in . A color reproduction of this image is included in the color insert of this book. As you can see more clearly there, the physical bounding box of the armature is colliding properly with the floor, but it is too small for the character.

The character sinks into the floor.

c15f013.tif

The collision radius on the armature

c15f014.tif

Showing physics visualization

c15f015.tif

Game play mode in Wireframe view with physics visualization

c15f016.tif
3. To fix the bounding-box problem, adjust the radius of the armature’s collision boundary so that the dotted line encompasses the full character, as shown in . In this case, the appropriate setting for the Radius value is about 1.7.

Adjusting the radius

c15f017.tif

Visualizing Physics
The Show Physics Visualization option in the Game drop-down menu (located in the User Preferences window header) is one of the most important troubleshooting tools you have for working with BGE. Collision behavior can be sensitive and require some finessing. Using the physics visualization tools will enable you to see where the collision boundaries for each object actually are so that you can ensure that they match up with their corresponding objects and interact properly with other physical objects in the environment.

Setting Up the Camera

If you press P while you are in Camera mode, or if you create a free-standing executable game using the game engine, the game will be displayed from the point of view of the active camera in the scene. There are several ways to ensure that the camera stays focused on your character. The simplest way is to simply parent the camera to the armature with the camera pointing at the armature. If you do this, the camera’s motion will be controlled directly by every movement of the armature. This is okay for some purposes, but the resulting camera movement is very stiff and the effect can be unnatural. For some 3D games, it is good to have a camera that can follow the character loosely and respond in a more natural way to the character’s movement, generally staying at a set distance but responding in a more flexible way to the character’s movements than if it were parented. This is what the Camera actuator is for.

The Camera actuator is a logic brick that can be set on a Camera object, as shown in . In this example, I use an Always sensor so that the Camera actuator is always active. The Camera actuator itself has a field for the name of the object the camera should be pointing toward, in this case Armature, and also fields for the height it should try to maintain, the minimal distance from the object it should be allowed to come, and the maximum distance from the object it should be allowed to get. Setting these values as shown in the figure will result in smoother and more-natural-looking camera behavior than you would get by simply parenting the objects.

The Camera actuator targeted on the Armature object

c15f018.tif

Using Properties, Messages, and States

In addition to sensors, controllers, and actuators, other features help make the Blender logic brick system a powerful programming language all in itself. These include properties, messages, and the state system, a result of the Yo, Frankie! open game project. Properties enable you to store and change values in the game engine environment. They serve a purpose directly analogous to variables in an ordinary programming language. Messages provide another way for logic bricks to communicate with other logic bricks, even when they are not directly connected. They can be useful for synchronization or cases when a logic brick should have an effect that is broadly recognized by other logic bricks. States enable a kind of meta-level of control over sets of logic bricks and can be used to enable or disable whole collections of logic bricks at once.

Setting Up Bad Guys

The game you’re putting together in this chapter is a simple maze game in which the goal is to collect Cone objects while avoiding evil wizard enemies. This section describes a simple setup for the bad guys that will provide a challenge to navigate without being too confusing to set up.

It is loosely based on a much more complex tutorial example provided by BlenderArtists.org user Mmph! His example uses a large number of logic bricks to create a rudimentary but convincing form of AI (artificial intelligence) and is very much worth checking out at . The method described in those tutorials is quite clever; however, it pushes the boundaries of what is advisable to do with logic bricks. For effects as sophisticated as AI, Python scripting is probably the least-cluttered and easiest way to work. Nevertheless, the simplified bad-guy movement logic presented here should give you a clear idea of how properties work and how they can be used to control characters’ behavior.

For the following tutorial, you can either append the BadGuy object to your own scene or use the badguy_nologic.blend file itself to follow the tutorial. The end result of the following steps can be found in the file badguy_logic.blend. The initial setup looks as shown in .

A bad guy and four path nodes

c15f019.tif

The path nodes are simply red cubes that have been resized to be about the height of the bad-guy character. As usual in the game engine, do your resizing in Edit mode and leave the object scale at 1. In the Mesh buttons, I’ve applied an empty UV texture to make the cones shadeless in the game engine, and I’ve colored them red using vertex painting. I suggest you create one first and add the logic described in the next section, and then copy it three times. Logic bricks are copied along with objects, so this approach will save you having to set up the logic for each path node individually.

Path Node Logic Bricks

The path nodes will be used to guide the bad guys’ movements around the board. At any given time, each bad-guy character will be set to track to a single node and move in the direction of that node. When the bad guy runs into a node, it will then switch to tracking toward the next node in the path. When the bad guy hits the last node, it will track back to the first node, completing a cycle around the course.

You need to set up some physical characteristics. Specifically, the path nodes should be set as static Ghost actors, as shown in . This will enable them to be passed through by other objects but also ensure that their collision boundaries are calculated when necessary.

Physics for path nodes

c15f020.tif

As shown in , the path node uses two properties. You can add these by clicking Add Game Property. Set the property type by using the drop-down menu for the property. Fill in the name and start value of the property in the appropriate fields. The Info icon button to the right of each property will toggle, displaying on and off. If the Info icon button is clicked, the property’s value will be displayed in-game if the Show Debug Properties option is chosen from the Game menu on the User Preferences header.

Properties for path nodes

c15f021.tif

The top property shown is named visible. It is an integer; therefore, Integer is selected from the property type drop-down menu. Its start value is 0. This property will be used to toggle the visibility of the path nodes in-game, in case this is necessary for troubleshooting. The second property is called pathnode. This property is used only to identify that the object is a path node. The property’s value will never be checked, only whether the object has this property. For this reason, it is okay to leave the type as the default float type, and the default value of 0.000.

The logic to toggle the visibility of the path nodes is shown in . The first sensor is a Keyboard sensor that responds to the I key. When the I key is pressed, it triggers a Property actuator. Property actuators come in three flavors: Assign, Add, and Copy. Assign is used to assign an arbitrary value to a property, Add is used to increment or decrement a property value, and Copy is used to copy a value from another property to a target property. In this case, you’ll use the Add option with a value of +1. This means that when the I key is pressed, the value of visible will be incremented by one.

Visibility toggle

c15f022.tif

The remaining sensors are all Property sensors, meaning that they trigger events whenever the relevant property has a specific value. The first one represents the case when the visible value is 0. It connects to a Visibility actuator set to Invisible. So by default, the path nodes will be invisible, because the start value of visible is 0. The next sensor down represents the case in which the value of visible is 1. This triggers a Visibility actuator set to Visible. Finally, the Property sensor for the case when the value is 2 triggers another Property actuator, this time an Assign actuator, which assigns a 0 value to the property, thus resetting the toggle.

After you’ve set up the logic on the first path node, copy the object three times and place the objects around the maze as shown in . Name the objects 1, 2, 3, and 4 so that they are positioned in numerical order.

Bad-Guy Logic Bricks

To keep things reasonably uncluttered, I’ll describe the bad-guy logic in several steps. The first thing to do is to set up the necessary physics and properties, as shown in . Like the main character, the bad guy will be a dynamic actor, but without rigid body physics. It will have two integer properties. The targ integer property represents the target node that the bad guy is presently moving toward. The inc property will eventually be used to determine whether the bad guy is traversing the path nodes in incrementing order or in decrementing order, thus moving clockwise or counterclockwise around the path. The wizard property will enable other game objects, particularly the main character, to identify the object as a bad-guy wizard. Finally, the bump property will be used to determine when a collision should make the bad guy reverse its direction.

Bad-guy wizard physics and properties

c15f023.tif

The basic move logic for the bad guy in the forward (incrementing) direction is shown in Figures 15.24, 15.25, 15.26, and 15.27. These four figures all show the same logic but with different bricks open for viewing. In , you can see the Always sensor, which is connected to the Motion actuator. This ensures that the bad-guy wizards continue moving forward at all times.

Bad-guy motion logic

c15f024.tif

In , the sensor is activated if the targ property’s value is 1 and triggers an Edit Object actuator with the Track To option selected. The target object in the OB field is 1. This means that while the value of targ is 1, the bad guy will continue to aim (and move) in the direction of the object called 1. Analogous logic bricks must be added, as shown, to correspond with cases when the targ value is equal to 2, 3, and 4.

Bad-guy tracking logic

c15f025.tif

shows the means by which the targ value itself is incremented. A Ray sensor is used to determine whether the BadGuy object has struck a node. If so, a Property actuator of type Add increments the targ value by one (+1). When the targ value reaches 5, a Property logic brick of the Assign type is used to assign the value of 1 to the targ property, resetting it.

The logic for this is shown in .

Bad-guy increment logic

c15f026.tif

Bad-guy node-reset logic

c15f027.tif

The final bad-guy logic will toggle the clockwise/counterclockwise direction of the bad guys by incrementing the inc value. This will happen whenever the bad guy runs into an object with a bump property (this of course includes other bad-guy objects). Because they are dynamic objects, the bad guys could bump against each other and be thrown off course or could be pushed into a position where they cannot reach the next path node. In this case, it is desirable to add a random switch so that from time to time they change directions arbitrarily. In this way, they are much more likely to free themselves if they become jammed somewhere, and it also leads to less-predictable patterns of movement.

To do this, you add logic to the Empty object as shown in . This logic has a Random sensor timed to emit once every 100 frames on average. It triggers a Message actuator with the subject line switch. In turn, the sensor shown in will fire when this message is emitted. In the final bad-guy motion logic, this random message triggers an increment or decrement in the targ value, depending on whether the bad guy is already moving in an incrementing or decrementing direction.

Random “switch” message on the Empty object

c15f028.tif

Bad-guy Message sensor

c15f029.tif

The full bad-guy motion logic is shown in . It is very much like the logic explained previously, except that logic is added for the cases in which the bad guys are traveling in the reverse (decrementing) direction around the path. There are too many logic bricks here to show them all unfolded, and furthermore, as you can see, the logic bricks here are already pushing the limits of what logical connections can be easily understood at a glance. I recommend that you take a close look at the file game.blend on the website for this book if you need further insight into how this logic works.

Full bad-guy motion logic

c15f030.tif

Note that if you watch the bad guys in action from the top view, the weaknesses of the very rudimentary path-finding algorithm used here quickly become apparent. The bad guys occasionally get stuck, and their movement becomes predictable. Nevertheless, the basic techniques described in this section will enable you to implement much more robust and sophisticated path-finding algorithms of your own.

Collecting Treasure and Racking Up Points

If you open the game.blend file on the website for this book, you’ll see the final game setup along the lines of . (The color insert in this book shows these figures in color.) I’ve placed three BadGuy objects on the path, one of them going the opposite direction from the other two (that is to say, one of them has an initial inc property value of 1, whereas the others have a value of 0). You’ll also see eight yellow cones and three green balls.

The final game setup

c15f031.tif

The object of the game is to collect the cones without hitting a wizard. When you collect all eight cones, you’ll see a congratulatory message, and the game will end. If you hit a wizard, the game will end and the message won’t be so congratulatory. The green balls make you bounce up and down, enabling you to get a view of the layout of the maze and the locations of the cones, and also protect you from the wizards. Of course, the effect of the green balls is temporary.

To set up these game-play features, you need to add logic to the cones and balls and add a bit more logic to the Empty object. The temporary protection you get from picking up the green balls will require the use of states in the character logic.

Using Cone, Ball, and Empty Logic

The logic associated with the Cone object is simple, as you can see in . A Near sensor is used, with a distance of 0.25 to determine when the character is close enough to touch the cone. The character is recognized by the char property. When the conditions on the sensor are met, two actuators are activated. The first is an Edit Object actuator set to End Object, which removes the Cone object from the scene. The second actuator is a Message actuator, which broadcasts a message with cone_touch as its subject. This message will be received by the Empty object and will result in incrementing the point counter on the Empty object, as shown in .

The logic on the ball is almost the same as the logic on the cone, as you can see in . The only difference is the subject of the message that gets sent. In this case, the subject is ball_touch. This will be received by the armature and will initiate the special protected state as described in the next section.

Cone logic

c15f032.tif

Empty logic

c15f033.tif

Ball logic

c15f034.tif

Using States

You’ve already seen the States panel in the Controllers column of the Logic buttons, but so far you haven’t made any use of it. States determine which controllers are active at any given time. Each controller and its connected sensors and actuators are associated with one state. Any combination of the 30 possible states can be active at any given time. States can be activated or deactivated by using a State actuator.

To see the States panel, click the small, round plus icon to the left of the controller logic brick. In , you can see the States panel. Each of the 30 light-gray squares represents a state. Darkened states such as the upper-left state in the figure are selected, meaning that their logic is currently visible. States can be selected or deselected analogously to layers in the 3D window, using Shift+LMB to select multiple states. States with a dot in them are states that have associated logic bricks. In the figure, the leftmost three states in the upper row all have logic bricks associated with them. The black dots represent states that are part of the initial state mask. That is, these are the states that will be active when the game begins. You can select the current initial states by clicking the Ini button to the right of the states, and you can select all states by clicking the All button. You can set the currently selected mask to be the default state mask by selecting Store Init State.

The States panel

c15f035.tif

To get the temporary protection effect from the green balls, three states will be used. The first state will contain the main logic described previously for the character. It will also contain the logic for what to do when a green ball is touched. The first state will be active at initialization. When the green ball is touched, the second state is deactivated (subtracted) and the third state is activated (added), as shown in .

Character logic for state 1

c15f036.tif

The second state, shown in , will contain the logic for ending the game when the character hits a wizard. This state will also be active on initialization, because this is the default behavior. When this state is deactivated, the character can collide with the wizards without ending the game.

Character logic for state 2

c15f037.tif

The third state will contain an Always sensor connected to a Motion actuator that makes the character bounce up and down for as long as the state is active. It also contains a Delay sensor set to 1,000 frames that will connect to two State actuators: one that reactivates the second state and one that deactivates its own state, state 3. The state 3 logic is shown in .

Character logic for state 3

c15f038.tif

By selecting all three states, you can view all the logic for all three states. This can also be done by deselecting the State visualization filter at the top of each logic brick column. With all the states visible, the logic for the character looks like what’s shown in .

Complete character logic

c15f039.tif

Creating Special Effects with Textures

There are several useful techniques for creating special effects with textures that are not at all obvious to a casual user of Blender. This section describes two of the main ones: the use of textures to create dynamic text, and animated textures.

Creating Dynamic Text

You can use 3D text in the Blender game engine, but you have to convert it to a mesh in advance with Alt+C in Object mode. If you do this, be sure that the normals are pointing in the correct direction. Otherwise, your text, like any mesh face, will not be visible in the game engine by default. This may be a reasonable way to add text to your game. However, if you need your text to be dynamic, that is, if you want to be able to assign string values to the text on the fly as the game is played, mesh text will not work. For this, you need to use a texture.

To use texture-based text, you must have the font you want to use in a correctly formatted image texture. You can use the file arialbd.tga on the website for this book. Alternately, you can use any TrueType font to create your own texture file via the FTBlender application that can also be found on the website.

Preparing the Font

Preparing the font is simple when using FTBlender on Windows. Simply unzip the file FTBlender.zip from the website. The directory you create will contain a file called ftblender.exe and another file called ftpblender.blend. Place the TrueType font file in the same directory as these two files, as shown in .

A directory with a TrueType font and FTBlender

c15f040.tif

Open the ftpblender.blend file by double-clicking, and execute the Python script in that file with Alt+P. The ftblender.exe program will automatically be called and will create the appropriate layout for the font image file. Press F2 to save the image file as a Targa file, as shown in .

The rasterized font Targa file

c15f041.tif

Using a Textured Face for Dynamic Text

To use a textured face for dynamic text, follow these steps:

1. Add a plane to your scene. This works best if you go into Camera view with the 0 key on the number pad. Select Align To View in the Tool Shelf if you don’t have this option turned on by default. You should wind up with something along the lines of what you see in . Don’t scale the object.

Adding a plane to the Text scene

c15f042.tif
2. Split your work area window and open a UV/Image Editor window. In the 3D viewport, tab into Edit mode on the plane. In the UV/Image Editor, select Open from the Image menu and open the font Targa file you want to use. Select Textured View in the 3D viewport (you can do this by pressing Alt+Z).
3. In Edit mode, scale the plane so that the @ symbol shows on the plane. Make the fit as snug as possible on all sides of the symbol, and rotate the mapping if necessary to make the symbol appear right side up, as shown in . It is important that you do this in Edit mode and that you have not altered the shape of the plane in Object mode.

Mapping the plane to the @ symbol

c15f043.tif
4. Add a shadeless material to the Plane object. If you have your render engine set to Blender Game, there will be a Game Settings panel in the Material properties area. shows the settings for this. Be sure that Text is checked and Alpha Blend is selected in the drop-down menu.
5. In Object mode, enter the Logic buttons and add a property to the Plane object. Name the property Text and select String as the property type. In the Value field, enter the string you want as the text in your game. In the example in , the string is My Text. In the 3D viewport, this is displayed as shown in . Don’t worry about the superfluous @ symbol on the plane—this will disappear in the game environment.

Creating Animated Textures

The wizard bad guys in the game have a particular quality, as you can see by looking at or by running the game from the website for this book. Between their hands is an animated arc of electricity. This is accomplished by using an animated texture on a single face.

Material game settings

c15f044.tif

The Text property

c15f045.tif

Resulting dynamic text

c15f046.tif

Electric wizard bad guy

c15f047.tif

You’ve already seen how to create UV-mapped textures for the game engine and other purposes. It is important to realize that the same model can have more than one UV map associated with different portions of its mesh. When you do UV unwrapping with the E key in the UV/Image Editor, only selected faces are unwrapped and included in the mapping. In , the bad-guy body mesh is selected in Edit mode. The entire mesh except for the polygon face between the wizard’s hands is selected. The resulting UV unwrapping, along with its texture, is shown in .

Body mesh selected

c15f048.tif

Body UV map

c15f049.tif

An animated texture in the Blender game engine works by encoding several individual frames of animation in the same image. In the current example, the frames are positioned side by side in the texture-mapped image. The final animated texture consists of 10 frames. A single frame of the “electricity” animation is shown in . Nine other similar images were created in GIMP and saved as PNG files with alpha values (the checkerboard background represents transparency). The images are each 420 pixels wide.

Original electricity image

c15f050.tif

To animate these in the game engine, you need to create a new image file in which all 10 of the frame images are positioned side by side. They must be positioned exactly, down to a single pixel width, and so the final animated texture file will be 4200 pixels wide. In , the model is shown with the single face selected and active.

1. In the UV/Image Editor, add a new image with the animated texture file, as shown in . Note that only the first “frame” of the animation, that is to say the leftmost 420 pixels’ worth of the image, is mapped directly to the plane.

Electricity face selected and active

c15f051.tif

Electricity UV map

c15f052.tif
2. Position the vertices in the UV/Image Editor directly by selecting Image Properties from the View menu, selecting a single vertex, and inputting its X and Y coordinates. The leftmost vertices should be at X coordinate 0, and the rightmost vertices should be at X coordinate 420.
3. Finally, scroll to the Game Properties dialog panel, also found in the Tool shelf of the UV/Image Editor. Set the game properties as shown in . Both Animated and Tiles should be selected. Animated Start and End values should be 1 and 10, respectively, because the animation is 10 frames long. Enter 12 as the speed (12 frames per second is sufficiently fast for this kind of animation). Tiles should have an X value of 10, indicating that the image is repeated 10 times horizontally.

Game properties

c15f053.tif
4. Finally, set the material’s Game properties values as shown in . Deselect Backface Culling to ensure that the texture is visible from both the front and the back of the face.

Material game properties

c15f054.tif

After you have all this set up, your animated texture will come to life when you press P to start the game engine.


Boro-Toro: An Award-Winning, Wii-Controlled, Physical-Puzzle Game in BGE
One of the 2008 winners of Dare to Be Digital (the United Kingdom’s premier student game-design competition), was Boro-Toro—a beautifully designed and original horizontal-scrolling puzzle game that uses Blender’s built-in Bullet physics with an optional Wii controller to provide terrific game-play effect. The game was created by DarkMatter Designs, a team composed of students from Wolverhampton University. Each member of the team was responsible for specific areas of the design and production of the game to complete the complex, multilevel game within the competition’s 10-week timeframe. The team consisted of Adam Westwood (project lead/designer/texture & UI artist), Graham Ranson (programmer), Matthew Booton (programmer/composer), Owen Schwehr (artist/animator), and Yves Wheeler (programmer)—none of whom had had any experience working with Blender when the project began. They kept a video blog of their progress, which can be viewed on YouTube at the following URL:
A report on the project, including a video trailer and a link to the game itself, can be found here:
As one of the three top winners of the competition, Boro-Toro was nominated for the 2009 British Academy of Film and Television Arts (BAFTA) award for video game design.

Working with Sound in the BGE

No game-creation tool would be complete without some way to incorporate interactive sound effects. Blender offers powerful options for working with sound. In this section, you will learn the basics of how to add a 3D sound effect.

To set up a simple 3D sound effect, follow these steps:

1. Select the Cube object in the 3D space and add a Sound actuator, as shown in . The Sound actuator is shown in . Click Open and navigate to the .wav file on your hard disk to load the sound file.

Adding a sound actuator

c15f055.tif

A sound actuator brick

c15f056.tif
2. The logic consists of an Always sensor, an And controller, and a Sound actuator, with the name of the sound from the Audio window entered in the SO field. Set the playback mode to Loop Ping Pong in the drop-down menu, as shown in . This will play the sound repeatedly, but every other individual playback will be reversed, creating a seamless, continuous sound. Press P to enter the game play mode, and you should hear the sound of bubbles rising.

Logic for the sound loop

c15f057.tif
3. To demonstrate the effect of 3D sound, add some simple motion logic to control the movement of the cube. Set up Keyboard sensors for the up, right, left, and down arrows, and connect them with Motion actuators moving the cube positively and negatively along the x- and y-axes, as shown in . This will enable you to “drive” the cube around in a rudimentary way. If you haven’t done so already, select 3D sound on the Sound actuator logic brick panel.

Motion logic for the cube

c15f058.tif

You’re all finished setting up the 3D sound. When you run the BGE now, you will find that the sound’s volume is dependent on the proximity of the Cube object to the camera. Be sure that you are in the Camera view (press 0 on the number pad) when you enter the game play mode.

You now know the basics of working with sound. Experimenting with the options available on the Sound actuator will deepen your knowledge. In Chapter 16 you will learn about accessing sound via the Python GameLogic API.

The Bottom Line

Control characters and scenes by using logic bricks. Interactive control in the Blender game engine is made possible by using the powerful logic brick system. With this system, you can use sensors, controllers, and actuators to trigger game events on a variety of types of input.
Master It In the chapter, you saw how to make the character walk forward and turn right. Set up a similar character that can turn left and walk backward as well.
Use properties, messages, and states to create complex interactions. Like a full-powered programming language, the BGE logic brick system enables you to store and modify values in the form of properties, to set up communications between different logic bricks using messages, and to control which logic bricks are active at what times by using states. In this way, complex interactions are made possible, limited only by the graphical nature of the logic bricks.
Master It Set up logic so that the wizards change directions whenever they hit the character, as well as when they hit each other.
Work with textures to create dynamic text and in-game 2D animations. Textures in the BGE can be used for a variety of interesting effects. Dynamic text whose content can be updated by logic bricks and in-game animations can be created by using specifically mapped textures with certain parameter settings.
Master It Use the method described in this chapter to create a 2D walk cycle animation. Use orthogonal renders of the character walk cycle you created in Chapter 9, “Compositing with Nodes,” and then put those renders together in a single image, using a 2D image-editing program such as Photoshop or GIMP. Map the image onto a plane in the game engine to create a walking 2D cutout character.
Incorporate sound effects into your game environment. Sounds can be controlled by Sound actuators similarly to other effects in the BGE. Special features exist to automatically control the sound on the basis of its distance from the camera.
Master It Browse the free sound files website and find some other interesting sound effects. Follow the steps in this chapter to add a new 3D sound to a moving object in the 3D space.
Назад: Part V: Mastering the Blender Game Engine
Дальше: Chapter 16: Python Power in the Blender Game Engine

lookforrent
Буду знать! Оцените туристический портал lookfor.rent
JbnvJinge
12 month loans cash now cash loans in winchester tn cash advance in dubai
androidinfoSa
Знать достаточно свежие публикации у сфере планшетов и наблюдать презентации планшетов Андроид пользователи смогут на разработанном сайте запись телефонных звонков , который окажет помощь для Вас находиться в теме последних выпусков мировых марок в операционке Android и продажи задекларированной устройств. Популярный ресурс выдает потребителям совершенно популярные предметы обсуждения: мнение экспертов про телефоны, оценка пользователей, обновление, апки для персональному смартфону, ОС Андроид, ответы на популярные вопросы также различные основные содержание, какими интересуются регулярно. Стоит коротко увидеть новый телефон и выделить уникальные характеристики? Вовсе не AndroidInfo.Ru преград - у основной строчке возможно кликнуть модель либо ключевое слово затем одержать с вашего задания подходящую параграф совместно с фотоотчетом плюс описанием преобладающего функций. В случае если юзер есть несомненного ценителя выпусков смарт устройств по операционке Андроид Android , здесь регистрация поможет юзерам ни разу не выпустить каждую единую добавленную новость у области умных систем. Будет изобилие всего увлекательного также развивающего для всем ценителей инноваций новой эры.
Anciwhish
buying paper custom written papers
DbgvAmurn
dissertation research research methodology dissertation