From BlenderWiki

Jump to: navigation, search
Downloads

Get the .blend files ZIP file used in this book (286.3M)

You can get this book in other formats, too (updated 20110215, archive.org hosting): read online: PDF, download: PDF, Epub, Kindle/mobi, Daisy, DjVu


Reference

The reference section will be your guide to exploring the Blender 3D game engine further after following the tutorials. To learn modeling and linear animation refer to the books mentioned in the appendix.

Real-time Materials

Game menu material options

There are different options on how to use materials for real time-content in Blender. All different kinds have specific advantages and disadvantages. The material system in Blender is now nearly complete usable in the game engine, however these materials need a good graphics cards.

Because of the deep impact on the speed of your game you probably need to make a decision what kind of material you want. In the Game menu you will find options to switch between the materials.

The following sections will explain the material options in the Game-menu.


Texture Face Materials

Texture Face Materials are the most basic materials in the game engine. Basically they only provide basic Materials (color) or one texture.

Features like lighting, specularity, hardness are working on vertex level so for low poly objects you will see artifacts in the lighting or in the specularity spot.

For a basic material, add a new one in the Material Buttons F5 or choose an existing one. Then change colors or other attributes. The object will be lit according to the lights (see also #Lamps in the game engine) in the same layer.

To add a texture we have to use UV texturing, see #UV Texturing. The texture will be mixed with the material color (only in the game engine not in the 3d view). To get vertex lighting we need to set the faces to "Light" in the Texture Face Panel in the Edit Buttons F9. Use the "Copy"-button to copy the Active Face Mode from the active to all selected faces. Beside the mixing with the plain material color it is also possible to use vertex-colors, see #Vertex Paint.

Blender Multitexture Materials

With these materials it is possible to have more up to three texture channels on an object. These textures can mix in different kind of ways. This makes it possible to have simple pre rendered light maps or faked reflections (using EnvMaps). Especially helpful is the possibility to bake the render into the texture, this can be done in the "Render"-menu.

Lighting, specularity, hardness for Blender Multitexture Materials is calculated on vertex level.

GameKit2 Reference 13-02 TexturesMulti.png
GameKit2 Reference 13-03 MeshPanelUVTex.png

You need to add a material with more than one texture channel. Then assign two or three textures to it, set the texture blending mode to one of the supported modes: Add, Multiply, Subtract, Divide or Mix. For Mix you need to adjust the Col: slider too.

Exclamation mark.png
Be sure to uncheck "UseAlpha" in the texture or the mixing will not produce the correct results!

The texture coordinates should come from one ore more UV Textures, which you can add and manage in the Edit Buttons F9, "Mesh"-panel.


Examples:

  • Multitexture.blend (the supported mixing modes)

GLSL Materials

GameKit2 Reference 13-04 GLSL ViewGameRender.png

Blenders GLSL Materials are the newest development for real time 3D and interactive display in the 3DViews. In the game engine you exactly get what you see in the 3D Views and it even almost looks like rendered. The purpose of this system is to stick closely to the material system as in Blender's internal renderer. Only a subset of the material options are supported, with hopefully more in the future, but the ones that are supported should give nearly identical results. Some advanced features like ray tracing are not likely to be added given that graphics card don't support them efficiently yet.

The main supported features are:

  • All material diffuse and specular shaders.
  • Diffuse and specular ramps.
  • All nodes, except for the dynamic node and limited support for material node.
  • Image textures only with few options.
  • A subset of the texture mapping options.
  • All lamp types except area, and basic support for shadow buffers.
  • Unlike Multitexture materials, most material and light settings are currently not animateable with GLSL materials. The limitations:
  • All objects will compute the lighting for all lamps, even if they are far away or on another layer. Hence it is important to keep the number of lamps as low as possible. For example for outdoor scenes, two sun or hemi lamps can illuminate the whole scene already.
  • The game engine supports maximum two UV layers and no compatible Orco texture coordinates.

GLSL Materials Performance Tips

Since Blender's materials system was designed for off line rendering and the GLSL materials attempting to be compatible with the internal render, they may not render as fast as more optimized game engines. Therefore it is important to optimize the material and light settings for best performance:

  • If some settings are set to values like 0.001 or 0.98, the visual difference with settings 0.0 or 1.0 may be very small, but it makes it harder for Blender to optimize the shader. Therefore it is advised to set such settings to 0.0 or 1.0 so that the effect can be completely disabled and does not need to be computed at all.
  • Various material shaders are supported, but may perform very slow. Lambert and Phong are fastest, so if possible those should be used. Note that for specularity Cook Torr is the default, which can in many cases be switched to Phong without much difference.
  • Additionally it helps to disable specularity if it is not needed. Not only can the Spec value be set to 0.0 in materials, but it also helps to enable No Specular on lamps, so only one lamp affects specularity for example.
  • If an image does not have alpha, it can help to disable Use Alpha in the texture buttons.
  • Avoid slow texture or ramp blending modes, mix/add/subtract/multiply are the fastest, hue/saturation/value/color are very slow.
  • Alpha blending needs to be avoided if possible, and Clip Alpha is a faster alternative, see the #Game Engine Alpha Blending for more information.
  • For shadows, it is more efficient to bake them for the whole scene, and use an OnlyShadow spot lamp for the character. On this spot lamp it is best to set the shadow buffer size low, enable No Specular, set SpotBl to 0.0. Also then the Layer option for shadow can be enable so that the lamp only casts the shadow of the character.

Graphics Card Support

This implementation takes advantage of the OpenGL Shading Language (GLSL), and requires a graphics card and drivers that support it. The game engine already supported such GLSL shaders, though they had to be manually written. The following cards typically support it, though the earlier ones have restrictions on the complexity of materials and the number of lights. Be sure to install the latest graphics card drivers as they might fix bugs and improve performance.

  • ATI Radeon 9x00, Xx00, X1x00, HD2x00 and HD3x00 series and newer.
  • NVidia Geforce FX, 6x00, 7x00, 8x00, 9x00 and GTX 2x0 and newer.

Intel or VIA graphics cards, ATI Radeon cards older then the Xx00 series, and Nvidia Geforce cards older than the 6x00 series are unlikely to support this functionality well, unless through a slow software fall back. The game menu provides settings to disable things such as lights, advanced shaders or shadows which can help on older graphics cards or complicated scenes.

Game Engine Alpha Blending

Transprarent faces are always expensive in a real time environment. Therefor there are different modes which all have their limitations but differ in rendering speed.

For clarity, here is an overview of alpha sorting in the game engine, there are four transparency types in the game engine:

  • Opaque: solid, no transparency at all.
  • Alpha: transparency with values between 0-1, blends with faces behind it.
  • Add: like Alpha, but adds color rather than blends.
  • Clip Alpha: otherwise known as binary alpha, each pixel renders either completely opaque (when alpha > 0.5) or completely transparent (alpha <= 0.5).

Ideally one would not have to deal with such settings, but for good performance it is important to pick the right ones, since rendering with Alpha isn't as fast as Opaque. In many cases Clip Alpha can be used instead of Alpha while still being nearly as fast as Solid. For example for leaves one usually does not need partial transparency.

GameKit2 Reference 13-05 alphablending.png

These settings can be set per face in the Texture Face panel. Note that for GLSL materials, the ZTransp setting must be used to enable any alpha, consistent with the internal render engine. The Alpha/Add/Clip Alpha settings can then be used to specify the exact blending type.

One important thing to know is that for rendering faces with Alpha and Add correct, the faces must be sorted before rendering in every frame. This is only supported in the game engine, not in the Blender viewport, which means that faces with alpha will draw incorrect in some cases there. Clip Alpha does not require sorting, which is useful since sorting objects with many polygons is slow.

Sorting has to be enabled with the Sort option in the Texture Face panel. The reason alpha sorting has to be set separately is because of the performance hit, and some objects might still render OK without sorting, so it is not enabled by default.

Lamps in the game engine

GameKit2 Reference 13-07 AddLamp.png

Lamps are created with the Toolbox (SPACE->Add Lamp) you can then choose the type of the lamp.

For a selected lamp you can switch to the Lamp Buttons (F5) to change the properties of that lamp. These properties are the type of the lamp, the color, the energy, etc. Due to the fact that the game engine is fully integrated in Blender, there are some buttons which are only useful for linear animation.

Common settings for all lamp types are the energy, and the color (adjustable with the RGB sliders).

To allow a face to receive real-time lighting in Blenders game engine, the face has to be set to "Light" in the "Texture Face"-panel. With the layer settings for lamps and objects (Edit Buttons, F9) you can control the lighting very precisely. Lamps only affect faces on the same layer(s) as the lamp. Per Layer you can use eight lamps (OpenGL limitation) for real-time lighting.

Figure xx: Lamp Buttons, settings for Blenders game engine

Lamp types for the game engine

Lamp: Lamp is a point light source.

Spot: This lamp is restricted to a conical space. In the 3DView the form of the spotlight is shown with broken lines. Use the SpotSi slider to set the angle of the beam.

Sun: The "Sun" lamp type is a directional light. The distance has no effect on the intensity. Change the direction of the light (shown as a broken line) by rotating the lamp.

Hemi: Only supported with GLSL Materials! A "Hemi" lamp is a 180° constant light source. Great for fill light.

The "Lamp" and "Spot" lights can be sensitive to distance. Use the "Dist:", "Quad1:" and "Quad2:" settings for this.

GLSL Shadows

Dynamic shadows (moving objects or lamps) in the game engine are possible with GLSL Materials and Spot Lamps. Static shadows can be realized using light mapping techniques.

First enable GLSL Materials in the Game menu. Then assign a Blender Material to all the shadow receiving objects. Enter the Textured Mode with ALT-Z.

Use a Spot with "Buffer Shadow" enabled as lamp. Set the size of the spot (SpotSi) according to your scene. Note that shadow lamps can easily decrease the speed of your game. If your shadow is too jagged like in the image [!below], then you might increase the ShadowBufferSize. Try to keep both values as low as possible.

GameKit2 Reference 13-08 LampBuffSize.png

Bias: If the shadow is only partially visible or parts of your object don't cast a shadow on the object itself, then decrease the "Bias:" value.

Only Shadow: In some situations it is nice to have a shadow but avoid illumination caused by the lights source itself. Examples are character shadows where the shadow gives a visual hint how high a character is while jumping for example.

Exclamation mark.png
Use the "Layer" option (see below) in the "Shadow and Spot" Panel to avoid that other objects interfere with the characters shadow. If your character needs to rotate use Vertex Parenting to attach the lamp.

Layer Buttons:

  • Layer in the "Lamp"-panel: This lamp only shines on objects in the same layer(s) as the lamp. Also shadows are only received from this lamp if the object shares the layer with the lamp.
  • Layer in the "Shadow and Spot"-panel: Only Objects in the same layer casting shadow from this lamp.

Examples:

  • GLSL_Lamps.blend
  • GLSL_LayerLamps.blend
  • GLSL_Lamps_Bias.blend
  • GLSL_Lamps_OnlyShadow.blend

UV Texturing

The UV editor is fully integrated into Blender and allows you to uv-map textures onto the faces of your models. Each face can have individual texture coordinates and an individual image assigned. This can be combined with vertex colors to darken or lighten the texture or to tint it.

UV Mapping is the art of mapping a 2D image around a 3D object with few distortions as possible!

With GLSL Materials now nearly the whole material system is available in the game engine. However this also needs some attention with textures. For now it is not so simple as with the old Texture Face Materials to get two images on different faces on one object. With GLSL we need multi-materials for that.

For UV mapping you enter EditMode for your object (only mesh objects supported). It is recommended to use the Face Select Mode in the EditMode, however it is perfectly ok to select faces by selecting 3 or 4 vertices or 3 or four edges. All the powers of EditMode are usable (i.e. Border Select, Circle Select, see also the Select-menu).

We now need a UV coordinate for the object. This can be achieved in some ways depending on the way you work or what you prefer:

  • select faces, then assign or load an image in the UV/Image Editor
  • use "New" in the "Mesh"-panel in the Edit Buttons F9 to make a new UV Texture
  • unwrap the object using UKEY
GameKit2 Reference 13-09 FaceSpecials.png

STRG-F calls the "Face Specials"-menu

Important functions for UV mapping here:

  • Face Mode Set/Clear: setting the face modes, like Tex, Tiles, Light, Invisible, Collision etc. This can also be done in the "Texture Face"-panel in the Edit Buttons
  • UV Rotate/Mirror: Rotate/mirror the texture-coordinates


GameKit2 Reference 13-10 TextureFacePanel.png

In the "Texture Face"-Panel of the Edit Buttons F9 you will find these functions also, and more:

Face modes

Tex
This enables the use of textures. To use objects without textures, disable "Tex", then the material color will be used or paint the faces with VertexPaint.
Tiles
This indicates and sets the use of the tile mode for the texture, see Section #Texture Tiles
Light
Enables real-time lighting on faces. Lamps only affect faces of objects that are in the same layer as the lamp. Lamps can also be placed on more than one layer, which makes it possible to create complex real-time lighting situations. See also Section #Lamps in the game engine
Invisible
Makes faces invisible. These faces are still calculated for collisions, so this gives you an option to build invisible barriers, etc.
Collision
The faces with this option are evaluated by the game engine. If that is not needed, switch off this option to save resources.
Shared
With this option vertex colors are blended across faces if they share vertices.
Twoside
Faces with this attribute are rendered two sided in the game engine.
ObColor
Faces can have color that can be animated by using the ColR, ColG, ColB and ColA Ipos. Choosing this option replaces the vertex colors.
Halo
Faces with this attribute are rendered with the negative X-axis always pointing towards the active view or camera.
Billboard
Faces with this attribute are pointing in the direction of the active view with the negative X-axis. It is different to "Halo" in that the faces are only rotated around the Z-axis.
Shadow
Faces with this attribute are projected onto the ground along the Z-axis of the object. This way they can be used to suggest the shadow of the object without using expensive real-time shadows.
Text
Faces with this attribute are used for displaying bitmap text in the game engine, see Section #Bitmap Text
Sort
Enable sorting of faces for correct alpha drawing. Note this is slow, use Clip Alpha whenever possible!
Opaque
Normal opaque rendered faces. The color of the texture is rendered as color.
Add
Faces are rendered transparent. The color of the face is added to what has already been drawn. Black areas in the texture are transparent, white are fully bright. Use this option to achieve light beam effects, glows or halos around lights. For real transparency use the next option "Alpha".
Alpha
The transparency depends on the alpha channel of the texture.
Clip Alpha
The transparency depends on the clipped alpha channel of the texture. (See also #Game Engine Alpha Blending)


GameKit2 Reference 13-11 CopyFaceSelected.png

The "Copy" buttons will always copy the Face Modes from the active face (dotted highlight) to the selected (pink highlight) faces. "CopyUV", "CopyTex" and "CopyColor" are copying UVs, texture and color from the active face to the selected faces.

In the "Copy Face Selected" menu called by CTRL-C you find more helpful functions to copy face properties.


Unwrapping

Unwrapping helps you to find a mapping from the 2D image to your 3D Object. A plane or a cube are easy to map, but with more organic and round objects like bottles, spheres or faces you need help in unwrapping. Usually the automatic unwrapping is the base and the artist then optimizes the result.

The UV Calculation menu is called out of Edit Mode with UKEY, all selected Faces are taken into calculation.

GameKit2 Reference 13-12 UVCalculationMenu.png
Unwrap
Unwraps the object taking seams into account
Cube Projection
Cubic projection (good base for walls, houses, technical devices)
Cylinder from View
Cylindrical projection (bottles, tires)
Sphere from View
Spherical projection (planets, marbles)
Project from View
The UV coordinates are calculated using the projection of the 3DWindow (good base for manually tweaking the result)
Project from View (Bounds)
The UV coordinates are calculated using the projection of the 3DWindow and then scaled to fit into the image dimensions.
Reset
Resets the UV coordinates of the selected faces
Click project from face
With three mouse clicks you can interactively set the uv coordinates in the 3DView
Follow Active (quads)
The quads of an object are unwrapped. Good for complex rectangular buldings. With the option "Loop Average" the face areas will be taken into account.
Lightmap UVPack
Method to unpack complex objects to use the map for light maps.
Unwrap (smart projections)
Powerfull unwrap method for mechanical and architectural objects.
GameKit2 Reference 13-13 UVCalculationPanel.png

In the "UV Calculation"-panel of the Edit Buttons F9 you can fine tune some parameters for unwrapping.

Image Aspect
Scales the unwrapping to the texture aspect
Transform Correction
With this option, the UV stays intact during an edge slide
Cube Size and Cyl Radius
Adjusts the size or radius for cubic or cylindrical unwrapping
Unwrapper (Conformal/Angle Based)
Unwrapping method
Fill Holes
Fill holes to prevent overlaps inside the unwrap
View Aligns Face/Top/Obj
Align the sperical/cylindrical unwrapping to the equator, pole or to the object align itself
Polar ZX/ZY
Polar 0 is X or Y for cylindrical or spherical unwrap
Seams

Seams are important for a good unwrapping. They define the edges where the unwrap algorithm is "cutting" the mesh apart. Place seams so that they are not noticeable or at a place where the material or texture changes much. Try to match the face areas in the projection with the faces of the 3d object.

Select the edges you want the seam to be and do CTRL - EKEY -> Mark Seam. To clear a seam use CTRL - EKEY -> Clear Seam.

UV/Image Editor

Anatomy of the UV/Image Window:

GameKit2 Reference 13-14 UVImageEditor.png
GameKit2 Reference 13-15 UVViewProperties.png


GameKit2 Reference 13-16 UVsMenu.png
View menu
Basic functions for the window, including zoom, maximize etc.

In the View Properties panel you can find nice functions to help you while working with UVs. Deactivate the "Face"-button to switch of the display of faces which can occlude your sight on the object and the image. "Repeat Image" helps you with tiling the image on the objects faces. "UV Stretch" will give you a visual hint how much your image gets distorted. Also note the possibility to set and read the position of the 2D Cursor.

Image menu
Basic image functions for load, save, pack etc. Also place for Python helper scripts.
Select menu (only availble when the mesh is in EditMode)
This menu contains special selection methods.
UVs menu

This menu contains many useful functions for working with UVs. It is beyond the scope of this chapter to explain everything here.

Working with UV Coordinates

As soon as you have a UV Texture on your object, you can work with it in the UV/Image Editor. UV vertices are represented with yellow (selected) or pink (unselected) points, connected by lines , just like in EditMode.

There are almost the same tools to work with the UV vertices as you are used to from the EditMode. Grab with GKEY, rotate with RKEY, scale with SKEY etc.

Unlike in meshes all UV faces (triangle or quad) have their own vertices, there is no sharing between vertices, because we need to be able to move any faces where ever we want. However, because it is often needed to move vertices together, an option is enabled by default to stick vertices together for easy editing. You can choose this behavior in the UV/Image Editor header:

GameKit2 Reference 13-17 StickyUVSelection.png
Shared Vertex
This will stick 3d vertices which are shared by face in the mesh. Usually you don't want to separate such vertices in the UV coordinates, because this will generate seams in the texture on the object.
Shared Location (default)
Vertices in the UV coordinates will be moved together when they share the same place (in a 5 pixel range)
Disable
Move vertices freely

Texture Tiles

Texture Tiles can be used to have more textures in one image an still be able to repeat textures on the objects. This is quite useful to save texture memory on older systems. The other use is to have simple animated textures.

Load a tiled texture into the UV/Image Editor, unwrap your object and assign the texture. Open the "Real-time Properties"-panel in the View-menu.

GameKit2 Reference 13-18 TextureTileUVEd.png

Now set "X:" and "Y:" according to the number of tiles in your texture and activate "Tiles". In EditMode you can now select the tile you want to use with SHIFT-LMB from the texture. It is now possible to use the normal UV editing tools and so for example scale up to have the tile repeated on your object.

For a simple texture animation you load a tiled texture on your object, then also set "X:" and "Y:" according to the number of tiles in your texture, no need to activate "Tiles" this time. Instead activate "Anim" and set the "Sta:" and "End:" to the desired values (End = X * Y). Finally set the speed (in frames per second) of the animation with "Speed:". You should now see a texture animation in your game. For a GLSL Material you also need a Blender Material and a Texture with your animation, then you could for example animate a Nor map to get real ripples on your water object.

Exclamation mark.png
Texture Tiling Animation only works for Texture Face Materials and GLSL Materials.

Examples:

  • TextureTiling.blend
  • TileAnim.blend
  • TileAnimGLSL.blend

Bitmap Text

GameKit2 Reference 13-18.1 TextureFacePanel.png

Blender has the ability to draw text in the game engine using special bitmap fonts textures. These bitmap fonts can be created from a TrueType or a Postscript outline font. See [1] for how to make your own. On DVD are some textures with bitmap fonts to try.

To get bitmap text or numbers displayed on a single face you need a special bitmap with the font rendered onto it. UV map the first character ("@") of the text-bitmap onto your text object (usually a plane). In the "Texture Face"-panel in the Edit Buttons F9 activate "Text" for all faces of your text object.

Then create a property named "Text" for your object. The property can be any type, so a Boolean Property will also be rendered as "True" or "False". For testing use a String-property and enter some text. Then start the game engine to see the results.

Vertex Paint

Vertex Paint Panel in the Edit Buttons F9

To start VertexPaint press VKEY or select the VertexPaint mode in the 3DView Header. The selected object will now be drawn solid. You can therefore now draw on the vertices of the object while holding LMB, the size of the brush is visualized by a circle while drawing. RMB will sample the color under the mouse pointer.

Enter the Edit Buttons F9 to see the “VertexPaint”-panel. Here you can also find more options to control VertexPaint:

R, G, B: The active color used for painting. Can also be set by using the Color Picker called by a LMB-click into the color field (see below)

Opacity: The extent to which the vertex color changes while you are painting.

Size: The size of the brush, which is drawn as a circle during painting.

Paint Modes

GameKit2 Reference 13-20 ColorPicker.png
Mix
The manner in which the new color replaces the old when painting: the colors are mixed.
Add
The colors are added.
Sub
The paint color is subtracted from the vertex color.
Mul
The paint color is multiplied by the vertex color.
Blur
Blurs the color according to the surrounding colors
Lighter
Paint over darker areas only
Darker
Paint over lighter areas only

Color field: A LMB click calls the color picker

SetVCol: Sets all vertices to the chosen color

All Faces: Paint on all faces inside the brush

VertexDist: This specifies that the extent to which the vertices lie within the brush also determines the brush's effect.

Normals The vertex normal (helps) determine the extent of painting. This causes an effect as tough you were painting with light.

Spray: Continues to add color while holding LMB and moving the mouse

Set: The "Mul" and "Gamma" factors are applied to the vertex colors of the Mesh.

Mul: The number by which the vertex colors are multiplied when "Set" is pressed.

Gamma: The number by which the clarity (Gamma value) of the vertex colors are changed when "Set" is pressed. You can choose on which faces you like to paint with the Painting Mask, called by FKEY or the icon GameKit2 Reference 13-21 PaintMask.png in the 3DView header. You can now select faces with the RMB, SHIFT-RMB, Border- or Circle-Select. Painting will now only occur on the selected faces. When the Painting Mask is active, you can choose with the Buttons "Faces", "Edges" and "Hidden Edges" how the faces or edges should be displayed while painting. This especially helps while staring to paint on a solid colored object.

Texture Paint

GameKit2 Reference 13-22 PaintProperties.png

To start Texture Paint select the Texture Paint Mode in the 3D Window header or out of the UV/Image Editor. Depending from where you activated Texture Paint you are now ready for painting either in the 3D View on your objects, or in the UV/Image Editor on your texture.

Exclamation mark.png
Texture Paint needs a UV textured object to work. You also need to unpack a packed texture first.

In the UV/Image Editor you paint like in a 2D paint application, in the 3D View you actually painting on the 3d object depending on ho the faces are oriented in 3D space.

You can now paint holding the LMB. RMB will sample the color located under the mouse pointer.

GameKit2 Reference 13-23 PaintPanel.png
GameKit2 Reference 13-24 2DPaintPanel.png

In the 3D View you can call the "Paint Properties"-panel with NKEY. Here you can adjust the color. Using the FKEY you can switch on a paint mask, meaning you can only paint on the selected faces. Faces are selected like in Edit Mode, RMB selects, SHIFT-RMB adds, you can also use Border Select or Circle Select.

In the "Paint"-panel in the Edit Buttons F9, you can also choose between different paint modes and mix modes. Further you can adjust the opacity, size, falloff and spacing of you brush strokes. It is also possible to add or recall brush settings or to paint using a different texture.

The "Image Paint"-panel has similar options. But aside of that you can also clone draw a different texture onto your texture.


Resource Handling

For publishing and easier handling of Blender's files, you can include all resources into the saved file. Normally textures, samples and fonts are not included in a file while saving. This keeps them on your disk and makes it possible to change them and share them between files. But if you want to distribute a file it is possible to pack these resources into the Blendfile, so you only need to distribute one file, preventing missing resources.

The functions for packing and unpacking are summarized in the "External Data"-menu. You can see if a file is packed if there is a little "parcel" icon to the right in the menu bar. After you packed a file, all new added resources are automatically packed (AutoPack).

When working with textures, sounds or fonts you will notice a pack-icon near the File- or Datablock-Browse. This icon allows you to pack/unpack the file independently.

GameKit2 Reference 13-25 ExternalData.png

External Data menu entries

Pack into .blend file
This packs all resources into the Blendfile. The next save will write the packed file to disk.
Unpack into Files
This unpacks all resources to the current directory. For textures a directory "textures" is created, for sounds a "samples" directory and fonts are unpacked to "fonts".


GameKit2 Reference 13-26 UnpackFiles.png

A menu will request further options. Be careful with the options overwriting files.

Use files in current directory
This unpacks only files which are not present in the current directory. It creates files when necessary.
Write files to current directory
This unpacks the files to the current directory. It overwrites existing files!
Use files in original location
This uses files from their original location (path on disk). It creates files when necessary.
Write files to original location
This writes the files to their original location (path on disk). It overwrites existing files!
Disable AutoPack, keep all packed files
This disables AutoPack, so new inserted resources are not packed into the Blendfile.
Ask for each file
This asks the user for the unpack options of each file.
Make all Paths Relative
This option changes all file paths so that they address the file in a relative way. So you can move your scene between different computers without caring for drives letters or such.
Make all Paths Absolute
This makes all paths absolute.
Report Missing Files
Reports missing files. A text buffer "missing_files.log" is created and contains informations about the missing files.
Find Missing Files
With this option you can point Blender to a directory containing the missing files.

Blenders Game Engine

Technically speaking the Blender game engine is a framework with a collection of modules for interactive purposes like physics, graphics, logic, sound and networking. Functionally the game engine processes virtual reality, consisting of content (the world, it's buildings) and behaviors (like physics, animation and logic). Elements in this world - also called GameObjects - behave autonomously by having a set of tools called Logic Bricks, and Properties. For comparison, the Properties act as the memory, the Sensors are the senses, the Controllers are the brain and the Actuators allow for actions in the outside world (i.e. muscles).

At the moment, the Controllers can be scripted using python, or simple expressions. The idea is that the creation of logical behavior can be edited in a more visual way in the future, so the set of controllers expands with AI state machines, etc. Controllers could be split in control centers, like an audio visual center, motion center, etc.

In fact Blender contains two game engines. One is the older and depreciated engine called "Sumo" and the new game engine internally called "Ketsji". Sumo is still integrated inside Blender to enable older games to run. The new engine is accompanied by a physics engine called "Bullet" (Author Erwin Coumans also know as one of the original authors of "Ketsji", see [2]) which calculates the physical behaviors of the objects, like falling, forces and collisions.

Options for the game engine

GameKit2 Reference 13-27 GameMenu.png
Start Game
Starts the game, shortcut is PKEY. If there is more than one 3dView the cursor changes into a question mark and you can now choose the view the game should be started in.
Enable All Frames
Normally the game engine will try to play the game in 60 frames per second (fps), if the CPU or graphics power is not high enough the engine will start dropping frames to maintain the overall speed of objects. This can cause stutter in the playback or even cause errors in collisions. With "Enable All Frames" the movement of the objects will slow down, but no frame will be dropped. This option is also very useful when using the game physics for linear animation.
Generate Display Lists
This option can improve the performance of the game (esp. in big and complex levels) quite a lot. However on older graphics cards this can lead to errors.
Record Game Physics to IPO
The movements of game objects will be recorded into Ipo animations. Very helpful for complex physics based animations (rolling, falling, jumping, collisions etc.)
Show Framerate and Profile
This will display statistical informations during game play. Good for optimizing your game.
Show Physics Visualization
This option draws objects bounds and also shows the status of physical objects. Good for debugging and testing physics.
Show Debug Properties
This option enables the display of properties with the debug "D" button set in textured views. Wireframe and solid shaded views always display debug properties.
Texture Face Materials
Most basic material and texture system in Blender. See #Real-time Materials.
Blender Multitexture Materials
Advanced use of multiple textures for games. See #Real-time Materials.
Blender GLSL Matrials
Up to date material system. Requires modern graphics cards. See #Real-time Materials.
GLSL Material Settings
In the sub menu you can enable/disable features of the GLSL material system for performance reasons or compatibility with graphics cards.
Autostart
A .blend-file with this option will autostart the game after loading. To edit such a .blend you can prevent autostart with a command line option.

Other Game Engine Options

In the User Preferences window you will find some more options:

Mipmaps
Mip-mapping is a texture filter to avoid flickering in textures and to enhance performance, especially when viewed from distance or a flat angle. In some cases this filtering can be unwanted or can even cause a performance drop, so this can be disabled here.
Disable Game Sound
Disable game sound, helpful to avoid errors on computers without sound hardware.
GL Texture Clamp
With these options you can force textures to a specific size. This can help to enhance the performance on slow computers or older graphics cards.

Logic Buttons

The Logic Buttons are meant for making interactive 3d worlds in Blender. Blender is a complete development tool for interactive worlds including a game engine to play the worlds. All this is done without compiling the game or interactive world. Just press PKEY and it runs in real-time. The main window for working with the Blender game engine are the Logic Buttons F4 (GameKit2 Reference 13-28 LogicButtonsIcon.png). Here you define your Logic Bricks, which add the behavior to your objects.

Exclamation mark.png
The word "games" is here used for all kinds of interactive 3D-content; Blender is not limited to making and play games, you can also do for example scientific visualizations or interactive 3d-manuals.


Figure xx-y. Logic Buttons left part

The Logic Buttons can logically be separated in two parts. The left part contains global settings for GameObjects.

This includes settings for general physics, like the damping or mass. Here you also define wether an object should be calculated with the build-in physics, as an actor or should be handled as an object forming the level (like props on a stage).

Settings for GameObjects:

With the menu button defaulting to Static you can choose how the physics engine should thread your object:

No collision No collision detection for the whole object. Use this for objects which can never be touched by any dynamic object to save performance.
Static This object acts as surrounding for a level or as a prop (like on a stage). These objects are still movable with Logic Bricks or Ipos, dynamic objects will react on collision with them.
Dynamic These objects will follows the laws of physics, like falling, bouncing and colliding
Rigid body This option enables the use of advanced physics by the game engine. This makes it possible that spheres roll automatically when they make contact with other objects and the friction between the materials is non-zero. Other shapes will tip over, tumble etc.
Soft Body This makes an object a soft body.
Exclamation mark.png
If you only see few buttons, one labeled "Physics" you need to create a world in the Shading Context F5, World Buttons which also creates a physics environment.

The "Advanced" button will call a pop up which covers advanced settings for the chosen object type.

Depending on the object type other buttons will appear:

GameKit2 Reference 13-30 DynamicButtons.png
Actor This makes Static objects detectable for Near and Radar sensors. Dynamic and Rigid Body objects are always an actor.
Ghost Ghost objects that don't restitute to collisions, but still trigger a collision sensor.
Advanced Settings Clicking on this button will call a pop-oup menu containing advanced settings for the choosen object type. For dynamic objects it will contain
Margin Each physics object has a collision margin in which collisions are detected. This margin leads to a much more stable simulation. However, for small objects or special cases you might want to decrease this margin to avoid gaps between resting objects.
Clamp Velocity (except when totally still) with a minimum and maximum value (0 = disabled).
Mass The mass of a dynamic actor has an effect on how the actor reacts when forces are applied to it. You need a bigger force to move a heavier object. Note that heavier objects don't fall faster! It is the air drag that causes a difference in the falling speed in our environment (without air, e.g. on the moon, a feather and a hammer fall at the same speed). Use the "Damp" value to simulate air drag.
Radius The size of the bounding sphere for sphere bound objects. The bounding sphere determines the area with which collisions can occur.
No sleeping Disable auto (de)activation for dynamic objects. Usually a object will be deactivated until it gets moved or hit by another object to save performance. For character objects this behavior can be unwanted.
Damp General (movement) damping for the object. Use this value for simulating the damping an object receives from air or water. In a space scene you might want to use very low or zero damping, air needs a higher damping, use a very high damping to simulate water.
RotDamp Same as "Damp" but for rotations of the object.
Do FH The FH system allows floating and hovering objects. Use together with the FH settings in the DYN Materials section.
Rot FH Uses the fave normal of the ground object to rotate the object.
Anisotropic Anisotropic friction. This enables different friction along the axes of an object. Great for sliding/skiing etc.

For the advanced settings for soft body objects please look in the soft body section.

With the "Bounds"-button you can activate other bounds types than the default bounding-sphere:

GameKit2 Reference 13-31 Bounds.png
Box Bounding box around the objects extends.
Sphere or default (no Bounds button activated)
Spherical bounds, visualized by a dotted circle in the 3DView. The Radius can be changed in the "Radius:" field.
Cylinder Cylindrical bounds, good for wheels, bottles, cans etc.
Cone Cone shaped bounds.
Convex Hull Convex (outward bulging surface) hull around the actual shape of the object. No holes or inward bulges are calculated.
Triangle Mesh This makes concave objects possible, for performance it is still recommended to use compound objects
Compound Adds dynamic children (parented with CTRL-P to the main object) to the physics calculation

Below the object settings you define the Properties of a GameObject. These Properties can carry values, which describe attributes of the object like variables in a programming language. Use "ADD property" to add properties.

Properties

Properties carry information bound to the object, similarly to a local variable in programming languages. No other object can normally access these properties, but it is possible to copy Properties with the Property (Copy) Actuator (see #Property Actuator) or send them to other objects using messages (see #Message Body).

GameKit2 Reference 13-32 PropertyTypes.png

The big "ADD property" button adds a new Property. By default a Property of the float type is added. Delete a Property with its "Del" button. The Menu Button defines the type of the Property. Click and hold it with the left mouse button and choose from the pop up menu. The "Name:" text field can be edited by clicking it with the left mouse button. SHIFT-BACKSPACE clears the name. Important

Exclamation mark.png
Property names are case sensitive. So "Benoit" is not equal to "benoit".

The next field is different for each of the Property types. For the Boolean type there are two radio-buttons; choose between "True" and "False". The string-type accepts a string; enter a string by clicking in the field with the left mouse. The other types use a Number Button to define the default value. Use SHIFT-LMB for editing it with the keyboard, click and drag to change the value with the mouse.

Property types:

Boolean (Bool) This Property type stores a binary value, meaning it can be "TRUE" or "FALSE". Be sure to write it all in capitals when using these values in Property Sensors or Expressions.
Integer (Int) Stores a number like 1,2,3,4,... in the range from -2147483647 to 2147483647.
Float Stores a floating point number like 3.14159265.
String Stores a text string.
Timer This Property type is updated with the actual game time in seconds, starting from zero. On newly created objects the timer starts when the object is "born".

Example of some Logic

Figure xx-y: Example of some Logic Bricks

The right part of the Logic Buttons is the command center for adding logic to your objects and worlds. The logic consists of the Sensors, Controllers and Actuators.

Sensors are like the senses of a life form; they react on key presses, collisions, contact with materials (touch), timer events or values of properties.

The Controllers are collecting events from the sensors and are able to calculate them to a result. These are similar to the mind or brain of a life form. Simple Controllers just do an AND on the inputs. An example is to test if a key is pressed AND a certain time has passed. There are also OR Controllers and you can also use Python scripting and expressions in the Expression Controller to create more complex behavior.

The Actuator actually performs actions on objects. A Motion Actuator for example is like a muscle. This muscle can apply forces to objects to move or rotate them. There are also Actuators for playing predefined animations (via Ipos), which can be compared to a reflex.

The logic is connected (wired) by click and hold LMB on an outlet (sphere) then dragging the mouse to the inlet and release. Sensors to Controllers and Controllers to Actuators. After wiring you are immediately able to play the game! If you discover something in the game you don't like, just stop the game engine, edit your 3-D world and restart. This way you can drastically cut down your development time!

The Blender laws of physics

All objects in Blender with the "Dynamic" or "Rigid Body" option set are evaluated using the physics laws as defined by the physics engine and the user.

The key property for a dynamic object is its mass. Gravity, forces, and impulses (collision bounce) only work on objects with a mass. Also, only dynamic objects can experience drag, or velocity damping (a crude way to mimic air/water resistance).

Exclamation mark.png
Note that for dynamic objects using dLoc and dRot may not have the desired result. Since the velocity of a dynamic object is controlled by the forces and impulses, any explicit change of position or orientation of an object may not correspond with the velocity. For dynamic objects it's better to use the linV and angV for explicitly defining the motion.

As soon we have defined a mass for our dynamic object, it will be affected by gravity, causing it to fall until it hits another object with its bounding. The gravity has a value of 9.81 by default, if you use one Blender unit as 1m and the mass of 1.0 as one kilogramm your objects will almost react as in the real world. You can change the gravitation in the World Buttons with the "Grav" slider. A gravity of zero is very useful for space games or simulations.

Damping can be used to simulate air drag. Damping decreases the velocity in percent (%) per second. Damping is useful to achieve a maximum speed. The larger the speed the greater the absolute decrease of speed due to drag. The maximum speed is attained when the acceleration due to forces equals the deceleration due to drag. Damping is also useful for damping out unwanted oscillations due to springs.

Exclamation mark.png
RotDamp does the same like Damp, but for rotational movements.
Exclamation mark.png
Use the "Damp:" and "RotDamp:" settings to suggest the drag of air or other environments. Don't use it to simulate friction. Friction can be simulated by using the dynamic material settings.

Do Fh and Rot Fh are a special way to simulate floating behaivior. Together with the dynamic settings in the Material this can be used to make boats or hovercrafts.

For some objects you need to have different friction in different directions. For instance a skateboard will experience relatively little friction when moving it forward and backward, but a lot of friction when moving it side to side. This is called anisotropic friction. Selecting the "Anisotropic" button in the Logic Buttons (F4) will enable anisotropic friction. After selecting this button, three sliders will appear in which the relative coefficient for each of the local axes can be set. A relative coefficient of zero denotes that along the corresponding axis no friction is experienced. A relative coefficient of one denotes that the full friction applies along the corresponding axis.

Dynamic Settings in the Material

Some physical attributes can be defined with the material settings of Blender. The Material Buttons can be accessed via the icon in the header of the Buttons Window or by pressing F5. Create a new material or choose an existing one with the Menu Button in the header.

In the Material Buttons you need then to activate the "DYN" button to see the dynamic settings:

GameKit2 Reference 13-34 DYNMaterial.png
Restitute: Objects will bounce on a collision. To control the amount of bounce add a material to the objects and set the Restitute value in the DYN section of the material to near zero for a soft material and near 1.0 for a very elastic material. Note that a very elastic ball will not bounce on a very soft material, so tune both materials.
Friction: Friction is a force tangent to the contact surface. The friction force has a maximum that is linear to the normal, i.e., the force that presses the objects against each other, (the weight of the object). The friction value denotes the Coulomb friction coefficient, i.e. the ratio of the maximum friction force and the normal force. A larger friction value will allow for a larger maximum friction. For a sliding object the friction force will always be the maximum friction force. For a stationary object the friction force will cancel out any tangent force that is less than the maximum friction. If the tangent force is larger than the maximum friction then the object will start sliding.
Fh Force: In conjunction with the "Do Fh" and/or "Rot Fh" in the Logic Buttons F4 you make an object float above a surface. "Fh Force" controls the force that keeps the object above the floor.
Fh Dist: "Fh Dist" controls the size of the Fh area. When the object enters this area the Fh mechanism starts to work.
Fh Damp: Controls the damping inside the Fh area. Values above 0.0 will damp the object movement inside the Fh area.
Fh Norm: With this button activated the object also gets a force in the direction of the face normal on slopes. This will cause an object to slide down a slope

Examples:

  • FhDemo.blend
  • Another way to have floating behaiviour is the Force Field Consraint, see ForceFieldConstraint.blend

Soft Bodies by Erwin Coumans

From Blender 2.48 onwards, the game engine features Bullet soft body simulation.

GameKit2 Reference 13-36 Softbody button.jpg

Soft Body Features

  • Flat cloth or volumetric soft bodies
  • Control over mass, friction, stiffness, shape matching and collision detection settings
  • Collision detection beween soft bodies as well as rigid bodies and static collision bounds of all types.
  • Attaching soft bodies against rigid bodies or using fixed pinning
  • Physics Debug Visualization of the dynamic soft body structures
  • Dynamically create new soft bodies using the Add Object Actuator

Creating a Bullet soft body

  • Choose "Soft Body" in the Logic Buttons F4
  • Choose a collision shape bounds for soft bodies, the bounds types for soft bodies are automatically restricted to convex hull or triangle mesh bounds.

Basic Soft Body Setting

GameKit2 Reference 13-114 Softbody button.png
LinStiff: Linear Stiffness, lower values create very flexible soft bodies, and larger values (1) more stiffness. Note that the shape matching feature and bending constraints will still keep extreme flexible bodies in shape.
Shape Match: when this option is enabled, Bullet will remember the original shape of each soft body, and tries to match the shape of a soft body, no matter how large the deformation has been.
kMT: Shape matching coefficient, how strong the soft body will return to its original shape. This only appear when the "Shape Match" option is enabled.
Friction allows to control the dynamic friction for soft bodies, in the range "[0..1]". 0.0 means no friction, soft bodies will slide.

Advanced Settings

Cluster Collision RS/SS: collision clusters can improve the collision detection, and it can avoid soft bodies passing through triangle meshes. Instead of colliding between individual vertices/nodes and faces, deformable convex clusters can be used. You can choose to use clusters between soft bodies (SS), or between soft body and rigid body (RS).
Cluster Iter: Higher values will create more detailed collision clusters. If you choose 1 it will use a single cluster using all vertices. This setting is only used if Clusters RB / SS is enabled.
Position Iter: position solver iterations. Use a higher value to improve the quality of position correction for soft bodies.

Pinning or attaching soft bodies

GameKit2 Reference 13-37 AddConstraintSB.png

You can use the Rigid Body Joint to attach a rigid body against a soft body. Similar to rigid body constraints, you can also pin/fix a soft body to make a vertex non-movable: just don't provide a second attachment object, or attach to a static object.

Right now, vertex groups are not supported, so you have to use Rigid Body Joint constraints.

  • Select a single soft body, or both a soft body and rigid body, using the "Add Constraint"-button in the Object Context F7, Object Buttons, "Constraint"-panel.
  • Enable the Show Pivot to see where the soft body will be pinned (px/py/pz frame). Bullet will automatically take the closest vertex/node to this pivot point.
  • You can use multiple constraints to pin/attach multiple parts of the soft body.
  • Python constraints can be used to create soft body constraints while the game is running. However, currently you cannot remove those constraints on-the-fly.


General soft body tips and some known issues

GameKit2 Reference 13-38 Debug visualization.png
GameKit2 Reference 13-39 Apply scaling.png
  • Blender 2.48 performs no collisions between soft bodies that have Clusters enabled, and soft bodies that have Clusters disabled. This will be fixed in future versions.
  • Subdivide the soft body triangle mesh to allow some more deformation: go into Edit Mode, select all vertices (AKEY or AKEY-AKEY) and hit subdivide.
  • UV Sphere meshes are not compatible with soft bodies, so use a Ico sphere instead.
  • If the mesh is too detailed, simplify the mesh using mesh decimation-modifier
  • Use Show Physics Visualization to debug issues with soft bodies, collision shapes etc. Enable the setting in the game menu.
  • When running the game with Show Physics Visualization enabled, you will notice the complex dynamic structures for soft bodies:
  • Don't use scaled meshes. Instead, use the Apply Scaling feature, or Apply Scale and Rotation by selecting the soft body object and pressing CTRL-A

Bullet Game Engine Features

The physics engine in Blender is called "Bullet" (Author Erwin Coumans, also know as one of the original authors of the Blender game engine, see www.bulletphysics.com) calculates the physical behaviors of the objects, like falling, forces and collisions. Bullet is a 3D Collision Detection and Rigid Body Dynamics Library for games. Open Source, ZLib license, free for commercial use, including Playstation 3.

The Bullet engine is used to drive many aspects of a game like GameLogic (Ray-, Near-, Collision Sensors), Constraints (Point, Hinge, Generic), it also contains a vehicle setup (only accessible via Python)

Bullet Physics Tips and FAQ

GameKit2 Reference 13-39 Radiusissue.png
Avoid Scaling
Don't scale your objects. Apply scale using CTRL-A. If you use Sphere-bounds, make sure the radius fits the sphere


Keep masses for dynamic objects similar
If an object of 100 kg rests on an object of 0.1 kg, the simulation will have difficulties. In order to avoid large mass ratios, keep mass of objects similar (in the order of a few kg)
GameKit2 Refernce 13-40 Bounds choosing.png
Assign the right bounds type
For a cylinder, choose cylinder, even for non-moving objects. Similar for a box etc. Convex Hull can approximate meshes for moving objects and static objects.


Don't use too many vertices in Convex Hull meshes
About 4 to 32 vertices should be fine. For more complex objects use simple proxy objects for the collision margin
GameKit2 Reference 13-41 Center inside mesh.png
Leave the center of the object in the middle of the mesh
The center (where the axis are) needs to be inside the mesh, not near to the boundary or outside!.


Leave the gravity to 10, don't make it too large
The physics simulation works better with smaller gravity, so if possible don't use large gravity.
Avoid very small dynamic objects (< 0.2 units)
Don't make dynamic objects smaller then 0.2 units if possible. For the default gravity, 1 unit equals 1 meter, so any 'side' of the objects should be bigger then that.
No large objects
Don't use large objects, or large triangles.
Don't use degenerate triangles
Triangles that are have extreme long sides as well as extreme short sides can lead to problems.
GameKit2 Reference 13-42 Sleeping deactivation.png
After a few seconds, the object doesn't move anymore. It doesn't interact with moving platforms etc.
You can manually activate an object, using python command 'object.restoreDynamics'. Or use the 'no sleeping' button. But don't use the 'no sleeping' button too much, perhaps just for the main character/car etc.


GameKit2 Reference 13-43 Vehicle wheelattach.png
How to setup a vehicle
Use the PhysicsConstraints module in Python, and create a special constraint on a rigid body.
  • For collision Bounds it is best to use Convex Hull Polytope. Remember to switch on collision for the chassis polygons!
  • Don't use box, because shifting the center of the box doesn't work.
  • Give the vehicle enough space to move: too narrow roads, too sharp corners and high street curbs and other obstacles that are difficult to avoid are very frequent mistakes which makes driving frustrating, rather then fun.

This constraint allows to add wheels, set tire friction, suspension, steering and so on.

There is a demo vehicle3_Steering fix.blend in the physics demos.

See the Python Vehicle Script for the code.

  • To improve (vehicle) simulation quality add this line to the python scrips:
PhysicsConstraints.setNumTimeSubSteps(2)
  • don't set friction of track and ground to zero, better lower the friction of car chassis This way you can add traffic cones and other interesting dynamic objects. Ground friction of 0 means bad physics quality.
  • Try to tweak the form factor (under No sleeping button) a little bit, but keep it close to 0.4. For example 0.45
  • For debugging to see that the ray cast for each wheel has correct position and direction use:
#draw the raycast lines
  PhysicsConstraints.setDebugMode(1)
  • Make sure you don't use overlays scenes and other camera effects (split screen/viewports) during debugging. The debug lines will not properly show up.
There is a small gap between the ground and my object
Except for boxes and sphere, there is indeed a tiny gap (0.06 by default) between objects. This gap allows the simulation to run smoother and more stable. It is not recommended, but you can reduce the gap with the "Margin" parameter in the Logic Buttons or using Python:
  controller = GameLogic.getCurrentController()
  owner = controller.getOwner()
  owner.setCollisionMargin(0.01)

You can also consider using margin of zero for static/non moving objects, and leave the default margin for dynamics objects.

I want higher quality simulation or create IPO key frames for animation
If you are on high performance machines or just rendering / creating key frames, and don't worry about real time you can increase the sub steps to improve quality of simulation, using a python script
  import PhysicsConstraints
  PhysicsConstraints.setNumTimeSubSteps(2)

default is 1. 2 or more make simulation more accurate.

Rigid Body Joints

GameKit2 Reference 13-44 ConstraintPanel.png

Rigid Body Joints can be added in the Object Buttons F7, "Constraints"-panel. Add a "Rigid Body Constraint" with the "Add Constraint" button. Constraints will keep a Object in a defined location or restrict the rotation around defined axes. However be careful, it is possible to break a constraint/joint using Dloc or dRot movements.

In common for all rigid body constraints are the position and rotation of the Pivot point (visualize with "ShowPivot"). Enter the name of the object to constrain into the field "toObject:". disable

The "No Col." button disables the collision detection between the two linked bodies. Often the bodies are (almost) overlapping, and collision detection conflicts with the other constraints.

Exclamation mark.png
Always remember that you add constraints to the parent object, not the constrained object (child)!

For debugging and visualizing a constraint it is very helpful to use the "Show Physics Visualization" from the Game-menu.

GameKit2 Reference 13-45 ConstraintTypes.png

With the "Rigid Body Constraint" chosen from the "Constraints"-panel you can specify different types of constraints:

Ball
Point to point constraint, also known as ball socket joint, limits the translation so that the local pivot points of two rigid bodies match in world space. A chain of rigid bodies can be connected using this constraint.
Hinge
Hinge constraint, or revolute joint, restricts two additional angular degrees of freedom, so the body can only rotate around one axis, the hinge axis. This can be useful to represent doors or wheels rotating around one axis. The user can specify limits and motor for the hinge.
Cone Twist
To create rag dolls, the cone twist constraint is very useful for limbs like the upper arm. It is a special point to point constraint that adds cone and twist axis limits.
Generic
A generic D6 constraint. This generic constraint can emulate a variety of standard constraints, by configuring each of the 6 degrees of freedom (dof). The first 3 dof axis are linear axis, which represent translation of rigid bodies, and the latter 3 dof axis represent the angular motion. For each axis:
  • Lowerlimit == Upperlimit -> axis is locked.
  • Lowerlimit > Upperlimit -> axis is free
  • Lowerlimit < Upperlimit -> axis it limited in that range

Examples:

  • RigidBodyJointTypes.blend
  • ConstraintHinge.blend

Sound Buttons

The Sound Buttons are used for loading and managing sounds for the Blender game engine. Currently only WAV files are supported.

Figure xx-y. The Sound Buttons

In the "Sound"-panel you can see the name of the Sound Object (here "SO:boird_flap.wav"). This name is set to the name of the sound sample by default, you can always rename it. With the Menu Button next to the "SO:" you can browse existing Sound Objects and load new Sound Objects. "Copy sound" makes a duplicate of the sound.

Below the "SO:" block you can assign already loaded samples to the Sound Object. So the Sound Object name doesn't have to be the name of the sample. For example you can use a Sound Object "SO:explosion" and then use "explosion_nuke.wav" later. You load samples using the "Load Sample" button. Using the Menu Button to the left of the file location, you can browse samples already loaded and assign one to the Sound Object.

Above the sample location, Blender gives you some basic information about the loaded sample, like the sample frequency, 8 or 16bit and if the sample is stereo or mono.

When the pack/unpack button (parcel) is pressed, the sample is packed into the *.blend file, which is especially important when distributing files.

The "Play" button plays the sound, you can stop a playing sound with ESC. The "Vol:" slider sets the volume of the sample. With the Pitch: value you can change the frequency of the sound. Currently there's support for values between half the pitch (-12 semitones) and double the pitch (+12 semitones). Or in Hertz: if your sample has a frequency of 1000 Hz, the bottom value is 500 and the top 2000 Hz.

The "Loop" button sets the looping for the sample on or off. Depending on the play-mode in the Sound Actuator this setting can be overridden. "Ping Pong" plays the sound forwards, then backwards in a loop, great for engine sounds.

The "3D Sound" Button activates the calculation of 3D sound for this Sound Object. This means the volume of the sound depends on the distance and position (stereo effect) between the sound source and the listener. The listener is the currently active camera.

The "Scale:" slider sets the sound attenuation. In a 3D world you want to scale the relationship between gain and distance. For example, if a sound passes by the camera you want to set the scaling factor that determines how much the sound will gain if it comes towards you and how much it will diminish if it goes away from you. The scaling factor can be set between 0.0, all positions get multiplied by zero, no matter where the source is, it will always sound as if it is playing in front of you (no 3D sound), 1.0 (a neutral state, all positions get multiplied by 1) and 5.0 which over accentuates the gain/distance relationship.

The "Listener"-panel in the Sound Buttons defines global settings for the listener. The listener is the current active camera. The "Volume:" slider sets the global volume of all sounds. The settings for the Doppler effect are currently not supported.

Performance and design issues

Computers get faster every month, nowadays nearly every new computer has a hardware accelerated graphics card. But still there are some performance issues to think about. This is not only a good design and programming style but also essential for the platform compatibility Blender provides. So to make a well-designed game for various platforms, keep these rules in mind:

  1. Don't use properties in combination with AND/OR/Expression controller as scripting language. Use the Python Controller for all more complex things
  2. Use as few inter-object LogicBrick connections as possible.
  3. Use ALT-D (instanced mesh for new object) when replicating meshes, this is better than SHIFT-D (copies the mesh).
  4. Alpha mapped polygons, especially sorted, are expensive, so use with care.
  5. Switching off the collision flag for polygons is good for performance. The use of "Ghost" is also cheaper then a regular physics object.
  6. Keep the polygon count as low as possible. Its quite easy to add polygons to models, but very hard to remove them without screwing up the model. The detail should be made with textures.
  7. Keep your texture-resolution as low as possible. You can work with hi-res versions and then later reduce them to publish the game.
  8. Polygons set to "Light" are expensive. Use with care or use lightning baked into textures.
  9. Instead of real-time lighting use VertexPaint to lighten, darken or tint faces to suggest lighting situations.
  10. Use simpler geometry for bounding and collision-bounds of objects
  11. Separate real time shadows to layers
  12. Use GLSL Materials with care, not all graphics cards will provide them (or fall back to a slow software rendering).

Game Logic Bricks

The game logic in Blenders game engine is assembled in the Realtime Buttons. Here you wire the different Logic Bricks together. The following is a brief description of all the Logic Bricks currently available.

Sensors

Sensors act like real senses; they can detect collisions, feel (Touch), smell (Near), view (Ray, Radar).

Always Sensor

The most basic Sensor is the Always Sensor. It is also a good example for the common buttons every sensor has.

Always Sensor with common elements for Sensors

The button labeled "X" deletes the Sensor from the game logic. This happens without a confirmation, so be careful. The Menu Button to the right of the delete button (here labeled "Always") allows you to choose the type of Sensor. Click and hold it with the left mouse button to get the pop up menu. Next is a Text Button, which holds the name of the Sensor. Blender assigns the name automatically on creation. Click the name with the left mouse button to change the name with the keyboard. Note

Name your Logic Bricks and Blender objects to keep track of your scenes. A graphical logic scheme can become very complex.

With the small arrow button you can hide the contents of the LogicBrick, so it only shows the top bar. This is very handy in complex scenes. Together with the State system (see #State System) this helps to keep track on complex logics.

The next row of buttons is used to determine how and at which frequency a Sensor is "firing". This topic is a bit complex, so we will give examples in more than one part of this documentation.

General things on sensors

The internal state of a sensor can only take two values: true or false. This state value is updated at each frame based on the external conditions that the sensor monitors: keyboard key press/release for the keyboard sensor, mouse movement for the mouse sensor, etc. At the start of each frame, the BGE runs through all the enabled sensors and updates their internal state. The sensor state remains unchanged through the rest of the frame processing. Transition between true/false states is the primary cause for triggering controllers. The Lvl and Pulse buttons can be used to generate more triggers but this is discussed in the a later section. The Inv button inverts the internal state: when the external condition is true, the internal state is false and vice-versa.

The direction of the transition (false/true or true/false) does not matter for triggering the controllers: either way, the controller is executed. Note that the controller is not executed immediately, but only when all enabled sensors have been updated. Regardless if multiple sensors are triggering the same controller, each triggered controller is executed only once. The internal state transition of a sensor triggers all the active controllers that are attached to it.

A controller that is executed will usually check the internal state of the sensors and take appropriate action. The logic controllers (AND, OR, XOR…) evaluate a formula using the state of all the sensors connected to them as input values; they do not use the transition information. The Python controller runs a user provided script and it is up to the script writer to check the state of the sensors using the Sensors “isPositive()” function. Note that the transition information is available through the “isTriggered()” function: the script writer can find out which of the sensor triggered the controller.

Pulse Modes and Lvl

The Lvl and Pulse buttons can be used to generate more triggers than just state transition.

Pulse Mode Buttons

There are two pulse buttons: one for the true state (left) and for the false state (right). When either button is selected, the frequency parameter "f:" determines at which frame interval the triggers are generated. A trigger is generated every frequency+1 frame. If the frequency parameter is 0, a trigger is generated on every frame. If the false(true) state pulse button is selected, the repeated triggers are produced when the sensor internal state is false(true). The pulse triggers are synchronized with the state transition: the first pulse trigger will arrive frequency+1 frame after the state transition. If both buttons are selected, repeated pulses are produced all the time but are still synchronized with the state transitions.

Different Pulse Mode Settings on a Keyboard Sensor
Exclamation mark.png
Before activating any pulse mode in the Sensor, try first without, this can save much performance, this is especially important with the Always Sensor. If you still need a pulse mode, think if you can raise the f: (frequency) setting, this can also save much performance.
Exclamation mark.png
If none of the mode buttons are activated the Always Sensor fires exactly one time. This is very useful for initializing stuff at the start of a game.

Lvl button: This button has only an effect when entering a state (when the state to which the sensor is connected is being activated due to a state actuator). Normally, a sensor generates an event (activates the controller) only when there is a transition in its internal state. When the Lvl button is selected, the sensor will always generate an initial event, whether positive or negative, based on the current sensor state. Example: you have a keyboard sensor that controls a motion actuator; you want the motion actuator to be immediately activated even if the key is already pressed when entering the state, so select the Lvl button.

Limitation: for the time being, this works reliably only if the sensor is connected to a single state. In a future version, it will work even if the sensor is used by multiple states.

Examples:

  • PulseModesDiagramm.blend (visualizes the Pulses and their values)
  • MoveCertainDist.blend (different uses of Pulse-Modes with the Motion Actuator)
Common Sensor Python Functions
returns Function Explanation
integer getFrequency() The frequency for mode sensors
bool getInvert() True if this sensor activates on negative events.
bool getUseNegMode() True if the sensor is in negative mode.
bool getUsePosMode() True if the sensor is in positive mode.
bool isPositive() True if this sensor brick has been activated.
setFrequency(freq) Sets the frequency for mode sensors.
setInvert(invert) Sets if this sensor activates on positive (true) or negative events.
setUseNegMode() Sets negative mode.
setUsePosMode() Sets positive mode.
bool getLevel() Returns whether this sensor is a level detector or a edge detector.
bool isPositive() True if this sensor brick is in a positive state.
bool isTriggered() True if this sensor brick has triggered the current controller.
reset() Reset sensor internal state, effect depends on the type of sensor and settings.
setLevel(level) Set whether to detect level or edge transition when entering a state.
bool isA() Allows to check if a python object is of a certain type. For example, if you get an object from the scene's object list, you can check if this object is of type lamp: if ob.isA("KX_LightObject"): ...

All Sensors provide these functions.

Delay Sensor

GameKit2 Reference 13-50 DelaySensor.png

The Delay sensor generates positive and negative triggers at precise time, expressed in number of frames. The delay parameter defines the length of the initial OFF period. A positive trigger is generated at the end of this period. The duration parameter defines the length of the ON period following the OFF period. There is a negative trigger at the end of the ON period. If duration is 0, the sensor stays ON and there is no negative trigger. The sensor runs the OFF-ON cycle once unless the repeat option is set, then the OFF-ON cycle repeats indefinitely (or the OFF cycle if duration is 0).


Delay Sensor Python Functions
returns Function
setDelay(delay) Set the initial delay (in frames) before the positive trigger.
setDuration(duration) Set the duration (in frames) of the ON pulse after initial delay and the generation of the positive trigger.
setRepeat(repeat) Set the sensors repeat mode.
integer getDelay() Return the delay parameter value.
integer getDuration() Return the duration parameter value
bool getRepeat() Return the repeat parameter value

Keyboard Sensor

GameKit2 Reference 13-51 KeyboardSensor.png

The Keyboard Sensor is one of the most often used Sensors because it provides the interface between Blender and the user.

The mode buttons are common for every Sensor so they have the same functionality as described for the Always Sensor.

By activating the "All keys" Button, the Sensor will react to every key. In the "Hold" fields you can put in modifier keys, which need to be held while pressing the main key.

The Keyboard Sensor can be used for simple text input. To do so, fill in the Property which should hold the typed text (you can use Backspace to delete chars) into the "Target:" field. The input will be active as long the Property in "LogToggle:" is "TRUE".

Python methods:

Keyboard Sensor Python Functions
returns Function
integer getKey() Returns the key code this sensor is looking for.
setKey(keycode) Set the key this sensor should listen for.
list of key status. keycode, status getPressedKeys() Get a list of keys that have either been pressed, or just released this frame (when the Sensor is triggered)
list of key status. keycode, status getCurrentlyPressedKeys() Get a list of currently pressed keys that have either been pressed, or just released. With this function you will get all pressed keys even if the Sensor is not triggered anymore.

Import the GameKeys module (see #GameKeys Module) to have symbolic names for the keys.

Mouse Sensor

GameKit2 Reference 13-52 MouseSensor.png

Currently, the Sensor is able to watch for mouse clicks, mouse movement or a mouse over. To get the position of the mouse cursor as well you need to use a Python-script.

To get the coordinates of the mouse it is necessary to use Python, see the examples.

Python methods:

Common Mouse Sensor Python Functions
returns Function
integer getXPosition( ) Gets the mouse's X-position
integer getYPosition( ) Gets the mouse's Y-position

Use the Menu Button to choose between the Mouse Sensor types:

GameKit2 Reference 13-53 MouseSensorTypes.png

Left/Middle/Right Button

The sensor gives out an event when the correlate mouse button is pressed.

Wheel up/down

The sensor gives an event when the mouse wheel is moved up or down.

Movement

The sensor sends out an event when the mouse is moved.

The following to mouse over modes are working as follow: a ray is fired from the mouse pointer into the scene (see examples section below on how to make the mouse pointer visible in a game). The results of the ray to object collision can be used in several ways, this reflects in the python functions for the mouse over modes.

Mouse over

The Sensor sends an event when the mouse pointer is over the object which carries the Sensor. To make mouse over works as expected, ensure to start the game in a Camera view!

Mouse over any

The Sensor sends an event when the mouse pointer is over any object (with collision faces). To make mouse over any works as expected, ensure to start the game in a Camera view!
Mouse Over Any Sensor Python Functions
returns Function
list [x, y, z] getHitNormal() Returns the normal of the detected face
KX_GameObject getHitObject() Returns game object the mouse is over
list [x, y, z] getHitPosition() Position in space where the ray hits the object
list [x, y, z] getRayDirection() Where the ray points to
list [x, y, z] getRayTarget() Returns the end point of the sensor ray.
list [x, y, z] getRaySource() Returns the start point of the sensor ray.

Examples:

  • Blends/Reference/MouseOverAdd.blend (Trackball View, Blender style, uses MMB)</code>
  • Blends/Reference/ShowMouse.blend (making the mouse pointer visible)</code>
  • Blends/Reference/MouseOverAdd.blend (adding objects at the mouse cursor)</code>
  • Blends/Reference/GetHitNormal.blend (use of getHitNormal())</code>

Touch Sensor

GameKit2 Reference 13-54 TouchSensor.png

The Touch Sensor gives an event when the object it is assigned to, touches a material. If you enter a material name into the "MA:" text field it only reacts to this material otherwise it reacts to all touches.

The Touch Sensor inherits from the Collision Sensor, so it provides the same methods, hence the method names. See also #Collision Sensor.

Touch Sensor Python Functions
returns Function Explanation
setProperty(name) Argument is a string containing the property or material name to collide with.
string getProperty() Returns the property or material to collide with.
KX_GameObject getHitObject() Returns the last object hit by this touch sensor.
list [KX_GameObject] getHitObjectList() Returns a list of all objects hit in the last frame.
bool getTouchMaterial() Returns true if this sensor looks for a specific material, false if it looks for a specific property.
setTouchMaterial(flag) Set flag to true to switch on positive pulse mode, false to switch off positive pulse mode.

Collision Sensor

GameKit2 Reference 13-55 CollisionSensor.png

The Collision Sensor is a general Sensor used to detect contact between objects. Besides reacting to materials it is also capable of detecting Properties of an object. Therefore you can switch the input field from Material to Property by clicking on the "M/P" button.

Collision Sensor Python Functions
returns Function Explanation
setProperty(name) Argument is a string containing the property or material name to collide with.
string getProperty() Returns the property or material to collide with.
KX_GameObject getHitObject() Returns the last object hit by this touch sensor.
list [KX_GameObject] getHitObjectList() Returns a list of all objects hit in the last frame.
bool getTouchMaterial() Returns true if this sensor looks for a specific material, false if it looks for a specific property.
setTouchMaterial(flag) Set flag to true to switch on positive pulse mode, false to switch off positive pulse mode.

Near Sensor

The near sensor reacts to actors near the object with the sensor.

GameKit2 Referencce 13-56 NearSensor.png
Exclamation mark.png
The near sensor only senses objects of the type "Actor" (a dynamic object is also an actor).

If the "Property:" field is empty, the near sensor reacts to all actors in its range. If filled with a property name, the sensor only reacts to actors carrying a property with that name.

You can set the spherical range of the near sensor with the "Dist" Number Button. The "Reset" value defines at what distance the near sensor is reset again.

The Near Sensor is a special case of a touch sensor, see #Touch Sensor for the Python methods and functions.

Radar Sensor

GameKit2 Reference 13-57 RadarSensor.png

The Radar Sensor acts like a real radar.

It looks for an object along the axis indicated with the axis pop up

GameKit2 Reference 13-58 RadarSensorAxis.png

If a property name is entered into the "Prop:" field, it only reacts to objects with this property.

In the "Ang:" field you can enter an opening angle for the radar. This equals the angle of view for a camera. The "Dist:" setting determines how far the Radar Sensor can see.

Objects can't block the line of sight for the Radar Sensor. This is different for the Ray Sensor (see #Ray Sensor). You can combine them for making a radar that is not able to look through walls.

Radar sensor is a near sensor with a conical sensor object. Please look at #Near Sensor for the common Python methods.


Radar Sensor Python Functions
returns Function Explanation
list [x, y, z] getConeOrigin() Returns the origin of the cone with which to test.
list [x, y, z] getConeTarget() |Returns the center of the bottom face of the cone with which to test.
float getConeHeight() Returns the height of the cone with which to test.

Examples:

  • RadarSensor.blend

Property Sensor

GameKit2 Reference 13-59 PropertySensor.png

The Property Sensor senses Properties attached to the object carrying the Property Sensor.

GameKit2 Reference 13-60 PropertySensorType.png

You can change the type with the pop up menu to Equal, Not Equal, Interval and Changed.

The "Equal" type Property Sensor checks for equality of the property given in the "Prop:" field and the value in "Value:". If the condition is true, it fires events according to the pulse mode settings.

The "Not Equal" Property Sensor checks for inequality and then fires its events.

The "Interval" type property sensor fires its event if the value of property is inside the interval defined by "Min:" and "Max:". This sensor type is especially helpful for checking float values, for which you can't depend on to reach a value exactly. This is most common with the "Timer" Property.

The "Changed" Property Sensor gives out events every time a Property is changed. This can, for example, happen through a Property Actuator, a Python script or an Expression.

Property Sensor Python Functions
returns Function Explanation
getType() Gets when to activate this sensor.
setType(checktype) Set the type of check to perform.
string getProperty() Return the property with which the sensor operates.
setProperty(name) Sets the property with which to operate.
string getValue() Return the value with which the sensor compares to the value of the property.
setValue(value) Set the value with which the sensor operates.

Random Sensor

GameKit2 Reference 13-61 RandomSensor.png

The Random Sensor fires a pulse randomly according to the pulse settings (50/50 pick). The Random is a so called "pseudo random", that means with the same seed the same sequence of numbers will be generated. This can be used to achieve "random" behavior that is the same on every game start. For more complex random functions see #Random Actuator.

Exclamation mark.png
With a seed of zero the Random Sensor works like an Always Sensor, which means it fires a pulse every time.


Property Sensor Python Functions
returns Function Explanation
setSeed(seed) Sets the seed of the random number generator.
integer getSeed() Returns the initial seed of the generator.
bool getLastDraw() Returns the last random number generated.

Ray Sensor

GameKit2 Reference 13-62 RaySensor.png

The Ray Sensor casts a ray for the distance set into the Number Button "Range". If the ray hits an object with the right Property or the right Material the Sensor fires its event.

Exclamation mark.png
Other objects block the ray, so that it can't see through walls. See also #Radar Sensor

Without a material or property name filled in, the Ray Sensor reacts to all objects.

Ray Sensor Python Functions
returns Function Explanation
KX_GameObject getHitObject() Returns the game object that was hit by this ray.
list [x, y, z] getHitPosition() Returns the position (in world coordinates) where the object was hit by this ray.
list [nx, ny, nz] getHitNormal() Returns the normal (in world coordinates) of the object at the location where the object was hit by this ray.
list [dx, dy, dz] getRayDirection() Returns the direction from the ray (in world coordinates)

Message Sensor

GameKit2 Reference 13-63 MessageSensor.png

The Message Sensor fires its event when a Message arrives. The "Subject:" field can be used to filter messages matching the given subject.


Message Sensor Python Functions
returns Function Explanation
setSubjectFilterText(subject) Change the message subject text that this sensor is listening to.
integer getFrameMessageCount() Get the number of messages received since the last frame.
list getBodies() Gets the list of message bodies.
string getSubject() Gets the message subject this sensor is listening for from the Subject: field.
list getSubjects() Gets the list of message subjects received.

See in section #Message Body on how to get the message body.

Joystick Sensor

GameKit2 Reference 13-64 JoystickSensorType.png

With the joystick sensor you can access joysticks, game pads and other gear connected to the computer. With logic bricks it is only possible to use button and to check if a joystick axis is moved a certain amount. To get the values of analog devices it is necessary to use a Python script, see the examples below.

With the type menu of the joystick sensor you can choose what the sensor sould sense.

Common for all Joystick Sensor types is "Index:", which tells Blender which joystick to use. The "All" button selects that all events for this type should trigger the sensor, especially usefull for Python scripts.

GameKit2 Reference 13-65 JoystickButtons.png

Button The number button "Number: 0" selects the joystick button to use.

GameKit2 Reference 13-66 JoystickAxis.png

Axis With "Number: 1" you choose which axis pair to use. With the menu right to the "Number: 1" Button you choose in which direction the stick needs to be moved for the sensor to fire an event. With "Threshold: 0" you can choose a value how much the stick needs to be moved to let the sensor fire. This is mostly used if a analog stick is used.

GameKit2 Reference 13-67 JoystickHat.png

Hat Some joysticks and game pads have a hat-controller, mostly used to change the view direction. With the "Number: 1" button you choose which head-controller to use. Hat-controllers can sense usually 8 directions, up, up+right, right, right+down, etc. The "Direction:" field gives the direction in a binary manner:

Direction Value
up 1
right 2
down 4
left 8

If you like to check for up and right you simply add the values, 1+2=3. Of course normally you can't press up and down at the same time on conventional sticks, but of course this way we are very flexible and have a 4 bit digital input we could use also for other things (robotic experiments, other types of input devices...).

Joystick Sensor Python Functions
returns Function Explanation
list getAxis Returns the current axis this sensor reacts to.
list getAxisValue Returns a list of the values for the current state of each axis.
integer getButton Returns the current button this sensor is checking.
list getButtonValue Returns a list containing the indicies of the current pressed state of each button.
list getHat Returns the current direction of the hat.
integer getIndex Returns the joystick index to use.
integer getNumAxes Returns the number of axes .
integer getNumButtons Returns the number of buttons .
integer getNumHats Returns the number of hats .
integer getThreshold Returns the threshold of the axis.
bool isConnected Returns True if a joystick is connected at this joysticks index.
setAxis Sets the current axis this sensor reacts to.
setButton Sets the button the sensor reacts to.
setHat Sets the hat the sensor reacts to.
setIndex Sets the joystick index to use.

Examples: - AnalogInput.blend (get analog input from a joystick)

Actuator Sensor

GameKit2 Reference 13-58 ActuatorSensor.png

The actuator sensor detects when certain actuator on the same object is triggered, useful for reducing the number of controllers and wires because you don't need to pass this information with properties anymore.

The sensor generates a positive when the corresponding sensor is activated and a negative when it is deactivated (the contrary if the Inv option is selected).

Actuator Sensor Python Functions
returns Function Explanation
string getActuator() Return the Actuator with which the sensor operates.
setActuator(name) Sets the Actuator with which to operate.

Notes:

  • Actuators are disabled at the start of the game; if you want to detect the On-Off transition of an actuator after it has been activated at least once, unselect the Lvl and Inv options and use a NAND controller.
  • Some actuators deactivates themselves immediately after being activated. The sensor detects this situation as an On-Off transition.

Examples:

  • See Pinnball tutorial (detection of an complete played Ipo)
  • This Actuator is also very to detect the loss of contact of the distance Constraint Actuator

Controllers

GameKit2 Reference 13-69 Controllers.png

Controllers act as the brain for your game logic. This reaches from very simple decisions like connecting two or more inputs, simple expressions, to complex Python scripts which can carry artificial intelligence.


Common Controller Python Functions
returns Function Explanation
list [SCA_ISensor] getSensors() Gets a list of all sensors attached to this controller.
SCA_ISensor getSensor(name) Gets the named linked sensor.
list [SCA_IActuator] getActuators() Gets a list of all actuators linked to this controller.
SCA_IActuator getActuator(name) Gets the named and linked actuator.
integer getExecutePriority() Returns the priority for this actuator
setExecutePriority(priority) Sets the priority for this actuator
string getName Get the given name
KX_GameObject getOwner() Gets the owner of the Controller
string getScript() Get the name of the Python script
setScript(scriptname) Set the name of the Python script
integer getState() Get the current state of the Controller
bool isA() allows to check if a python object is of a certain type. For example, if you get an object from the scene's object list, you can check if this object is of type lamp: if ob.isA("KX_LightObject"): ...

Simple Logical Controllers

GameKit2 Reference 13-70 ANDController.png The AND controller only passes an event if all inputs are true.

GameKit2 Reference 13-71 ORController.png The OR controller passes an event if any number of the inputs is true.

GameKit2 Reference 13-72 NANDController.png The NAND controller is an inverted AND controller: the output is true if any of the input is false.

GameKit2 Reference 13-73 NORController.png The NOR controller is an inverted OR controller: the output is false if any of the input is true.

GameKit2 Reference 13-74 XORController.png The XOR controller is an exclusive OR: the output is true if and only if one input is true and all the other inputs are false.

GameKit2 Reference 13-75 XNORController.png The XNOR controller is an inverted XOR: the output is false if and only if one input is true and all the other inputs are false.

The NAND, NOR and XNOR controllers are very useful to create complementary outputs to start and stop actuators synchronously.

Expression Controller

GameKit2 Reference 13-76 ExpressionController.png

With the Expression Controller you can create slightly complex game logic with a single line of "code". You can access the output of sensors attached to the controller and access the properties of the object.

Exclamation mark.png
The expression mechanism prints out errors to the console, so have a look there if anything fails.

Expressions

Expressions can be used in the Expression Controller and the Property Actuator.

Table: Valid expressions
Expression type Example
Integer numbers 15
Float number 12.23224
Booleans TRUE, FALSE
Strings "I am a string!"
Properties propname
Sensornames sensorname (as named in the sensor LogicBrick)


Table: Arithmetic expressions
Expression Example
EXPR1 + EXPR2 Addition, 12+3, propname+21
EXPR1 - EXPR2 Subtraction, 12-3, propname-21
EXPR1 * EXPR2 Multiplication, 12*3, propname*21
EXPR1 / EXPR2 Division, 12/3, propname/21
EXPR1 > EXPR2 EXPR1 greater then EXPR2
EXPR1 >= EXPR2 EXPR1 greater or equal EXPR2
EXPR1 < EXPR2 EXPR1 less than EXPR2


Table 26-3. Boolean operations
Operation Example
NOT EXPR Not EXPR
EXPR1 OR EXPR2 logical OR
EXPR1 AND EXPR2 logical AND
EXPR1 == EXPR2 EXPR1 equals EXPR2
Conditional statement: IF( Test, ValueTrue, ValueFalse )


Table 26-4. Expression examples
Expression Result Explanation
12+12 24 Addition
property=="Carsten" TRUE or FALSE String comparison between a Property and a string
"Erwin">"Carsten" FALSE A string compare is done

Python Controller

GameKit2 Reference 13-77 PythonController.png

The Python controller is the most powerful controller in game engine. You can attach a Python script to it, which allows you to control your GameObjects, ranging from simple movement up to complex game-play and artificial intelligence.

Enter the name of the script you want to attach to the Python Controller into the "Script:" field. The script needs to exist in the file or Blender will ignore the name you type.

Exclamation mark.png
Remember that Blender treats names as case sensitive! So the script "player" is not the same as "Player".

Python for the game engine is covered in #Game engine Python

Python Controller Functions
returns Function Explanation
string getScript() Gets the Python script this controller executes.
setScript(script) Sets the Python script this controller executes.

State System

States are a way to achieve complex logics without cluttering your Logic Buttons and having to redo already existing Logic Bricks. States are a group of Logic Bricks which get executed at a certain time or state (hence the name) of the game.

Imagine a character wandering around. There may be different materials for the ground (e.g. ice and sand), a different control method in water or air, etc. Without states you would now start to use Properties, Property-Sensors and Actuators to control what state the actor has. With the state system probably only one LogicBrick changes the state and you are done.

State internals (by Benoit Bolsee)

The state system is object based. The current state mask is stored in the object as a 32 bit value; each bit set in the mask is an active state. The controllers have a state mask too, but only one bit can be set: a controller belongs to a single state. The game engine will only execute controllers that belong to active states. Sensors and actuators don't have a state mask but are effectively attached to states via their links to the controllers.

Sensors and actuators can be connected to more than one state. When a controller becomes inactive because of a state change, its links to sensors and actuators are temporarily broken (until the state becomes active again). If an actuator gets isolated, i.e all the links to controllers are broken, it is automatically disabled. If a sensor gets isolated, the game engine will stop calling it to save CPU power. It will also reset the sensor internal state so that it can react as if the game just started when it gets reconnected to an active controller. For example, an Always sensor in no mode that is connected to a single state (i.e connected to one or more controllers of a single state) will generate a event each time the state becomes active. This feature is not available on all sensors, see the notes below.

State GUI

This system system is fully configurable through the GUI: the object state mask is visible under the object bar in the controller's colum as an array of buttons just like the 3D view layer mask. Click on a state bit to only display the controllers of that state. You can select more than one state with SHIFT-LMB. The "All" button sets all the bits so that you can see all the controllers of the object. The "Ini" button sets the state mask back to the objects default state. You can change the default state of objects by first selecting the desired state mask and storing using the menu under the "State" button.

GameKit2 Reference 13-78 StateMenu.png

If you define a default state mask, it will be loaded into the object state make when you load the blend file or when you run the game under the Blenderplayer. However, when you run the game with Blender, the current selected state mask will be used as the startup state for the object. This allows you to test specific state during the game design.

The controller displays the state they belong to with a new button in the controller header. When you add a new controller, it is added by default in the lowest enabled state. You can change the controller state by clicking on the button and selecting another state. If more than one state is enabled in the object state mask, controllers are grouped by state for more readability.

The new "Sta" button in the sensor and actuator column header allows you to display only the sensors and actuators that are linked to visible controllers.

A new state actuator is available to modify the state during the game. It defines a bit mask and the operation to apply on the current object state mask:

Cpy: the bit mask is copied to the object state mask.

Add: the bits that set in the bit mask will be turned on in the object state mask.

Sub: the bits that set in the bit mask will be turned off in the object state mask.

Inv: the bits that set in the bit mask will be inverted in the object state mask.

Things to note:

  • Although states have no name, a simply convention consists in using the name of the first controller of the state as the state name. The GUI will support that convention by displaying as a hint the name of the first controller of the state when you move the mouse over a state bit of the object state mask or of the state actuator bit mask.
  • Each object has a state mask and each object can have a state engine but if several objects are part of a logical group, it is recommended to put the state engine only in the main object and to link the controllers of that object to the sensors and actuators of the different objects.
  • When loading an old blend file, the state mask of all objects and controllers are initialized to 1 so that all the controllers belong to this single state. This ensures backward compatibility with existing games.
  • When the state actuator is activated at the same time as other actuators, these actuators are guaranteed to execute before being eventually disabled due to the state change. This is useful for example to send a message or update a property at the time of changing the state.
  • Sensors that depend on underlying resource won't reset fully when they are isolated. By the time they are activated again, they will behave as follow: Keyboard sensor: keys already pressed won't be detected. The keyboard sensor is only sensitive to new key press. Collision sensor: objects already colliding won't be detected. Only new collisions are detected. Near and radar sensor: same as collision sensor.

Actuators

Actuators are the executing Logic Bricks. They can be compared with muscles or glands in a life form.

Depending on the type or purpose of an Actuator, an Actuator can act differently on a pulse. Some inputs are more like keys (the get released when no pulse arrives) some act more like a switch (needs to be switched of by a pulse carrying a negative value). This is especially important for the Motion Actuator.

Common Actuator Python Functions
returns Function Explanation
integer getExecutePriority() Returns the priority for this actuator
setExecutePriority(priority) Sets the priority for this actuator
string getName() Get the given name
KX_GameObject getOwner() None
bool isA() allows to check if a python object is of a certain type. For example, if you get an object from the scene's object list, you can check if this object is of type lamp: if ob.isA("KX_LightObject"): ...

(Shape) Action Actuator

The Shape Action Actuator will play Actions or Shape Key animations in the game engine. If you add it to a mesh, it will add a Shape Action Actuator, if added to an Armature it will be an Action Actuator. Have a look at the examples below and the Character Animation tutorial.

GameKit2 Reference 13-79 ShapeActionActuator.png

Fill in the start and end frame of your action into the "Sta:" and "End:" fields.

Action play modes

Play: Plays the Action from "Sta" to "End" at every positive pulse the Actuator gets. Other pulses while playing are discarded.

Flipper: Plays the Action from "Sta" to "End" on activation. When the activation ends it plays backwards from the current position. When a new activation reaches the Actuator the Action will be played from the current position onwards.

Loop Stop: Plays the Action in a loop as long as the pulse is positive. It stops at the current position when the pulse turns negative.

Loop End: This plays the Action repeatedly as long as there is a positive pulse. When the pulse stops it continues to play the Action to the end and then stops.

Property: Plays the Action for exactly the frame indicated in the property entered in the field "Prop:".

Enter the name of your (Shape) Action into the field "AC:". Blender will blank the input if the entered name does not exist.

If you switch states the "Continue"-button becomes important. In case that the "Continue"-button is pressed, upon deactivation of the Actuator, the last played frame of the action will be stored and restored when the Actuator is enabled (because of a state switch) again.

In case you have more than on Action on your Object, "Blendin:" allows you to blend between the Actions. "Blendin:" is measured in numbers of frames.

Actions with lower "Priority:" will override Actions with higher priority. Keep in mind that the overriding Actions need to be lower in the Actuators stack.

Enter a Property name into the "FrameProp:" filed to get the actual frame number of the played action. This is very handy to synchronize the game with specific actions.

Action Actuator Python Functions
returns Function Explanation
setAction(action, reset=True) Sets the current action
setStart(start) Specifies the starting frame of the animation
setEnd(end) Specifies the ending frame of the animation
setBlendin(blendin) Specifies the number of frames of animation to generate when making transitions between actions
setPriority(priority) Sets the priority of this actuator
setFrame(frame) Sets the current frame for the animation
setProperty(prop) Sets the property to be used in FromProp playback mode
setBlendtime(blendtime) Sets the internal frame timer
setType(mode) Sets the operation mode of the actuator
setContinue(cont) Set the actions continue option True or False
integer getType() Returns the operation mode of the actuator
bool getContinue() When True, the action will always play from where last left off, otherwise negative events to this actuator will reset it to its start frame
string getAction() returns the name of the action associated with this actuator
float getStart() Returns the starting frame of the action
float getEnd() Returns the last frame of the action
float getBlendin() Returns the number of interpolation animation frames to be generated when this actuator is triggered
float getFrame() Returns the current frame number
string getProperty() Returns the name of the property to be used in FromProp mode.
setChannel(channel, matrix, mode=False) Sets the channel to use
setAction(action, reset=True) Sets the current action. action (string): The name of the action to set as the current action. reset: Optional parameter indicating whether to reset the blend timer or not. A value of 1 indicates that the timer should be reset. A value of 0 will leave it unchanged. If reset is not specified, the timer will be reset.
setStart(start) Specifies the starting frame of the animation. Parameters: start (float) the starting frame of the animation

Examples:

  • ShapeAction.blend (Shape and Armature Action playing in the game engine)

Motion Actuator

The motion actuator is meant to move objects. Depending if you have a non-dynamic (so not evaluated by the physic engine) or dynamic object (see Doc:Reference]) it changes its appearence a bit. So for non-dynamic objects the Simple Motion Actuator would look like:

GameKit2 Reference 13-80 MotionSimpleActuator.png

Because we operate in a 3D environment all parameters are for all three axis, so the numbers below are meant from left to right as X, Y and Z value of a parameter.

Loc: X, Y and Z value the object should be moved upon activation of the Actuator.

Rot: Rotation around X, Y and Z axis when the Actuator is activated. Normally you can look at this value as rotation speed. However if you need to rotate a certain amount of degrees you can use this formula to calculate the value for the Rot-parameter: Rot = Degrees / 50

With activated (default) "L"-buttons (L for local) all rotations and movements will be along the objects axes. With a deactivated "L"-button the movement or rotation will be along the world coordinates.

Notes:

  • The Motion Actuator needs a negative event to deactivate, see "examples/MoveCertainDist.blend"

For dynamic Objects there are much more options:

GameKit2 Reference 13-81 MotionSimpleDynActuator.png

Loc: X, Y and Z value the object should be moved upon activation of the Actuator.

Rot: Rotation around X, Y and Z axis when the Actuator is activated. Normally you can look at this value as rotation speed. However if you need to rotate a certain amount of degrees you can use this formula to calculate the value for the Rot-parameter: Rot = Degrees / 50

Exclamation mark.png
The movement and orientation of dynamic Objects is usually evaluated by the physics engine to simulate natural behaviors of the objects, e.g. falling and colliding with other objects. Using Loc/Rot for dynamic objects is not recommended unless you know what you are doing or you want to achieve a special effect.

Force: Dynamic objects have a mass, and you need a force to move them. This force can be set here for X, Y and Z axes.

Torque: Same as for Force but here a force to rotate the object

LinV: Sets a linear velocity of the object. This can be used to set a starting speed of an object, but it should not be used to actually move the object. When the "Add"-button is pressed the velocity will be added to the existing object velocity

AngV: Same as Linv but for rotational speed

Damp: Damp works only for LinV and AngV (linear and angular Velocity). It defines the time constant, in frames, to get to the specified velocity.

With activated (default for Loc/Rot/Force/Torque) "L"-buttons (L for local) all rotations and movements will be along the objects axes. With a deactivated "L"-button the movement or rotation will be along the world coordinates.

To avoid problems with objects getting faster and faster, or to allow more control over your game-physics there is another type of Motion Actuator, the Servo Control Actuator. You choose this type with the "Motion Type"-menu:

GameKit2 Reference 13-82 MotionServoActuator.png

This variant of the motion actuator allows to control speed with force. The control is technically of the type "PID" (Propotional, Integral, Derivate): the force is automatically adapted to achieve the target speed. All the parameters of the Servo Actuator are configurable. The result is a great variety of motion style: anisotropic friction, flying, sliding, pseudo Dloc, etc. This actuator should be used in preference to Dloc and LinV as it produces more fluid movements, avoids the collision problems with Dloc and interacts correctly with gravity unlike linV.

LinV : target speed as (X,Y,Z) vector in local or world coordinates (mostly useful in local coordinates).

Limit: the force can be limited along each axis (in the same coordinates of LinV). No limitation means that the force will grow as large as necessary to achieve the target speed along that axis. Set a max value to limit the acceleration along an axis (slow start) and set a min value (negative) to limit the brake force.

P: Proportional coefficient of servo controller, don't set directly unless you know what you're doing.

I: Integral coefficient of servo controller. Use low value (<0.1) for slow reaction (sliding), high values (>0.5) for hard control. The P coefficient will be automatically set to 60 times the I coefficient (a reasonable value).

D: Derivate coefficient. Leave to 0 unless you know what you're doing. High values create instability.

Notes:

Exclamation mark.png
The servo motion actuator applies forces, it is therefore not compatible with other actuators that sets the force too, i.e a simple motion force actuator or another servo motion. Although it is possible to combine two servo motion actuators that works on different axis.
Exclamation mark.png
This actuator is compatible with simple Drot motion actuator but not with LinV and Dloc motion.
Exclamation mark.png
This actuator works perfectly in zero friction environment: the PID controller will simulate friction by applying force as needed.
Exclamation mark.png
(0,0,0) is a valid target speed.
Motion Actuator Python Functions
returns Function Explanation
list [x,y,z,local] getAngularVelocity Gets the angular Velocity (AngV) set in the Actuator
list [x,y,z,local] getDLoc Gets the Loc set in the Actuator
list [x,y,z,local] getDRot Gets the Rot set in the Actuator
integer getDamping Gets the Damp set in the Actuator
list [x,y,z,local] getForce Gets the Force set in the Actuator
list [min,max,active] getForceLimitX Gets the force limit X as set in the Actuator (Servo Control)
list [min,max,active] getForceLimitY Gets the force limit Y as set in the Actuator (Servo Control)
list [min,max,active] getForceLimitZ Gets the force limit Z as set in the Actuator (Servo Control)
setForceLimitX Sets the force limit for the x-axis
setForceLimitY Sets the force limit for the y-axis
setForceLimitZ Sets the force limit for the z-axis
list [x,y,z,local] getLinearVelocity Gets the linear velocity set in the Actuator
list [x,y,z,local] getTorque Gets the torque set in the Actuator
setAngularVelocity() Sets the torque value
list [x,y,z] setDLoc(x,y,z,local) Set the values for the DLoc row, use local=0 to move along global axes
list [x,y,z] setDRot(x,y,z,local) Set the values for the DRot row, use local=0 to rotate around global axes
setDamping(damping) Damping for the linV/linRot
setForce(x,y,z,local) Set the values for the Force row, use local=0 to move along global axes
setLinearVelocity(x,y,z,local) Set the values for the linV row, use local=0 to move along global axes
setTorque(x,y,z,local) Set the values for the Torque row, use local=0 to rotate around global axes

Constraint Actuator

The Constraint Actuator offers different ways to constraint or inhibit a movement or degree of freedom. Use the "Constraint Type"-menu to choose between Location, Orientation and Distance.

GameKit2 Reference 13-83 ConstraintActuator.png
GameKit2 Reference 13-84 ConstraintActuatorType.png


Location

With the Constraint Actuator of the type "Location" you can constraint the location of an object in the 3d-space.

GameKit2 Reference 13-85 ConstraintActuatorLocLimit.png

First choose a axis at which you want to limit the movement. If you need to constraint an object on more axes, use more Constraint Actuators.

With the values under "Min" and "Max" you adjust the limits of the movement. The values are in Blender units.

"damp" controls how fast/hard (low values) or slow/soft (high values) the Actuator reacts on a position change of the object.

Notes:

Exclamation mark.png
for dynamic objects this Controller is of limited use because it will not define a hard border, instead have a look at #Reference
Exclamation mark.png
for dynamic objects try to use the Servo-Control Motion Actuator

Examples:

  • See the "Flying Buddha" demo (Buddha main character)

Distance

[!check Change!] This variant of the constraint actuator allows to set the distance and orientation relative to a surface. The controller uses a ray to detect the surface (or any object) and adapt the distance and orientation parallel to the surface.

GameKit2 Reference 13-86 ConstraintActuatorDistance.png

Damp: Time constant (in numbers of frames) of distance and orientation control.

Dist: Select to enable distance control and set target distance. The object will be position at the given distance of surface along the ray direction.

GameKit2 Reference 13-87 ConstraintActuatorDistanceDirection.png

Direction: chose a local axis as the ray direction.

Range: length of ray. Object within this distance will be detected.

N: Select to enable orientation control. The actuator will change the orientation and the location of the object so that it is parallel to the surface at the vertical of the point of contact of the ray.

M/P: Select to enable material detection. Default is property detection.

Property/Material: name of property/material that the target of ray must have to be detected. If not set, property/ material filter is disabled and any colliding object within range will be detected.

PER: Select to enable persistent operation. Normally the actuator disables itself automatically if the ray does not reach a valid target.

time: Maximum activation time of actuator. Zero means unlimited, values above zero meaning number of frames before automatic deactivation.

rotDamp: Time constant (in numbers of frame) of orientation control. Zero: use Damp parameter. Above zero: use a different time constant for orientation.

Notes:

  • If neither N nor Dist options are set, the actuator does not change the position and orientation of the object; it works as a ray sensor.
  • The ray has no "X-ray" capability: if the first object hit does not have the required property/material, it returns no hit and the actuator disables itself unless PER option is enabled.
  • This actuator changes the position and orientation but not the speed of the object. This has an important implication in a gravity environment: the gravity will cause the speed to increase although the object seems to stay still (it is repositioned at each frame). The gravity must be compensated in one way or another. the new servo control motion actuator is the simplest way: set the target speed along the ray axis to 0 and the servo control will automatically compensate the gravity.
  • This actuator changes the orientation of the object and will conflict with Drot motion unless it is placed BEFORE the Drot motion actuator (the order of actuator is important)
  • All parameters are accessible through Python.

Orientation

This variant of the constraint actuator allows to align an object axis along a global direction.

GameKit2 Reference 13-88 ConstraintActuatorOrientation.png

Damp: Time constant (in numbers of frames) of orientation control.

X,Y,Z: Global coordinates of reference direction.

time: Maximum activation time of actuator. Zero means unlimited, values above zero meaning number of frames before automatic deactivation.

Direction: chose a local axis as the ray direction.

GameKit2 Reference 13-89 ConstraintActuatorOrientationDirection.png

Notes:

  • (X,Y,Z) = (0,0,0) is not a valid direction
  • This actuator changes the orientation of the object and will conflict with Drot motion unless it is placed BEFORE the Drot motion actuator (the order of actuator is important). - This actuator doesn't change the location and speed. It is compatible with gravity.
  • All parameters are accessible through Python.

Force Field

  Log Message:
  -----------
  BGE patch: new force field constraint actuator
  
  A new type of constraint actuator is available: Force field.
  It provides a very similar service to the Fh material feature
  but with some specificities:
  - It is defined at the object level: each object can have 
    different settings and you don't need to use material.
  - It can be applied in all 6 directions and not just -Z.
  - It can be enabled/disabled easily (it's an actuator).
  - You can have multiple force fields active at the same time
    on the same object in different direction (think of a 
    space ship in a tunnel with a repulsive force field
    on each wall).
  - You can have a different damping for the rotation.
  
  Besides that it provides the same dynamic behavior and the 
  parameters are self explanatory.
  It works by adapting the linear and angular velocity: the
  dynamic is independent of the mass. It is compatible with
  all other motion actuators.
  
  Note: linear and anysotropic friction is not yet implemented,
  the only friction will come from the object damping parameters. 
  Support for friction will be added in a future revision.
  
Constraint Actuator Python Functions
returns Function Explanation
integer getDamp getDamp() Returns the damping parameter.
3-tuple getDirection getDirection() Returns the reference direction of the orientation constraint as a 3-tuple.
float getDistance getDistance() Returns the distance parameter
integer getLimit getLimit() Returns the type of constraint.
float getMax getMax() Returns the upper value of the interval to which the value is clipped.
float getMin getMin() Returns the lower value of the interval to which the value is clipped.
integer getOption getOption() Returns the option parameter.
string getProperty getProperty() Returns the property parameter.
float getRayLength getRayLength() Returns the length of the ray
integer getRotDamp getRotDamp() Returns the damping time for application of the constraint.
integer getTime getTime() Returns the time parameter.
setDamp setDamp(duration) - duration: integer Sets the time constant of the orientation and distance constraint. If the duration is negative, it is set to 0.
setDirection setDirection(vector) - vector: 3-tuple Sets the reference direction in world coordinate for the orientation constraint.
setDistance setDistance(distance) - distance: float Sets the target distance in distance constraint
setLimit setLimit(type) - type: integer 1 : LocX 2 : LocY 3 : LocZ 7 : Distance along +X axis 8 : Distance along +Y axis 9 : Distance along +Z axis 10 : Distance along -X axis 11 : Distance along -Y axis 12 : Distance along -Z axis 13 : Align X axis 14 : Align Y axis 15 : Align Z axis Sets the type of constraint.
setMax setMax(upper_bound) - upper_bound: float Sets the upper value of the interval to which the value is clipped.
setMin setMin(lower_bound) - lower_bound: float Sets the lower value of the interval to which the value is clipped.
setOption setOption(option) - option: integer Sets several options of the distance constraint. Binary combination of the following values: 64 : Activate alignment to surface 128 : Detect material rather than property 256 : No deactivation if ray does not hit target 512 : Activate distance control
setProperty setProperty(property) - property: string Sets the name of the property or material for the ray detection of the distance constraint. If empty, the ray will detect any colliding object.
setRayLength setRayLength(length) - length: float Sets the maximum ray length of the distance constraint
setRotDamp setRotDamp(duration) - duration: integer Sets the time constant of the orientation constraint. If the duration is negative, it is set to 0.
setTime setTime(duration) - duration: integer Sets the activation time of the actuator. The actuator disables itself after this many frame. If set to 0 or negative, the actuator is not limited in time.

Ipo Actuator

GameKit2 Reference 13-90 IpoActuator.png

The Ipo Actuator can play the Ipo-curves for the object that owns the Actuator. If the object has a child with an Ipo (in a parenting chain) and you activate "Child" in the Actuator, the Ipo for the child is also played.

The animation is played from "Sta:" to "End:" (in frames). If you enter a valid Property name in the "FrameProp:" field this Property will be updated with the current frame number of the Ipo played. Be carefull with the float Property type, this can hold non whole numbers, which should check with the "Interval"-Propery Sensor.

Exclamation mark.png
The Ipo in the game engine will be played with the speed indicated as "FPS:" (frames per second) in the Display Buttons F12 in the "Format"-panel.

The "Force" Button will convert the "Loc" Ipo curves into forces for dynamic objects. When pressed, the "L" Button appears which cares for applying the forces locally to the objects coordinate system. This can be used for a nice jumping action or similar.

The Add button, mutually exclusive with Force button. When selected, it activates the Add mode that consists in adding the Ipo curve to the current object situation in world coordinates, or parent coordinates if the object has a parent.

Scale Ipo curves are multiplied instead of added to the object current scale. If the local flag is selected, the Ipo curve is added (multiplied) in the object's local coordinates.

Delta Ipo curves are handled identically to normal Ipo curve and there is no need to work with Delta Ipo curves provided that you make sure that the Ipo curve starts from origin. Origin means location 0 for Location Ipo curve, rotation 0 for Rotation Ipo curve and scale 1 for Scale Ipo curve.

"Current object situation" means the object's location, rotation and scale at the start of the Ipo curve. For Loop Stop and Loop End Ipo actuators, this means at the start of each loop. This initial state is used as a base during the execution of the Ipo Curve but when the Ipo curve is restarted (later or immediately in case of Loop mode), the object current situation at that time is used as the new base.

For reference, here is the exact operation of the Add mode for each type of Ipo curve (oLoc, oRot, oScale, oMat: object's loc/rot/scale and orientation matrix at the start of the curve; iLoc, iRot, iScale, iMat: Ipo curve loc/rot/scale and orientation matrix resulting from the rotation).

Local Operation
Location
false newLoc = oLoc+iLoc
true newLoc = oLoc+oScale*(oMat*iLoc)
Rotation
false newMat = iMat*oMat
true newMat = oMat*iMat
Scale
false newScale = oScale*iScale
true newScale = oScale*iScale

Add+Local mode is very useful to have dynamic object executing complex movement relative to their current location/orientation. Of course, dynamics should be disabled during the execution of the curve.

Ipo play modes

Play Plays the Ipo from "Sta" to "End" at every positive pulse the Actuator gets. Other pulses received while playing are discarded.

Ping Pong Plays the Ipo from "Sta" to "End" on the first positive pulse, then backwards from "End" to "Sta" when the second positive pulse is received.

Flipper Plays the Ipo for as long as the pulse is positive. When the pulse changes to negative the Ipo is played from the current frame to "Sta".

Loop Stop Plays the Ipo in a loop for as long as the pulse is positive. It stops at the current position when the pulse turns negative.

Loop End This plays the Ipo repeatedly for as long as there is a positive pulse. When the pulse stops it continues to play the Ipo to the end and then stops.

Property Plays the Ipo for exactly the frame indicated by the property named in the field "Prop:".

Ipo Actuator Python Functions
returns Function Explanation
integer getEnd() Returns the frame at which the ipo stops playing.
bool getForceIpoActsLocal() Return whether to apply the force in the object's local coordinates rather than the world global coordinates.
bool getIpoAsAdd() Returns whether to interpret the ipo as additive rather than absolute.
bool getIpoAsForce() Returns whether to interpret the ipo as a force rather than a displacement.
integer getStart() Returns the frame from which the ipo starts playing.
integer getType() Returns the operation mode of the actuator.
set(type, startframe, endframe, mode?) type: Play, PingPong, Flipper, LoopStop, LoopEnd or FromProp (string) startframe: first frame to use (int) endframe : last frame to use (int) mode? : special mode (0=normal, 1=interpret location as force, 2=additive) Set the properties of the actuator.
setEnd(frame) frame: last frame to use (int) Set the frame at which the ipo stops playing.
setForceIpoActsLocal(local) local : Apply the ipo-as-force in the object's local coordinates? (KX_TRUE, KX_FALSE) Set whether to apply the force in the object's local coordinates rather than the world global coordinates.
setIpoAdd(add) flag (KX_TRUE, KX_FALSE), set whether to interpret the ipo as additive rather than absolute.
setIpoAsForce(force) interpret this ipo as a force (KX_TRUE, KX_FALSE) Set whether to interpret the ipo as a force rather than a displacement.
setProperty(propname) propname: name of the property (string) Set the property to be used in FromProp mode.
setStart(frame) frame: first frame to use (int) Set the frame from which the ipo starts playing.
setType(mode) mode: Play, PingPong, Flipper, LoopStop, LoopEnd or FromProp (string) Set the operation mode of the actuator.

Examples:

  • AddIpo.blend
  • Jump.blend
  • IpoFrameProperty.blend

Camera Actuator

GameKit2 Reference 13-91 CameraActuator.png

The Camera Actuator tries to mimic a real cameraman. It keeps the actor in the field of view and tries to stay at a certain distance from the object. The motion is soft and there is some delay in the reaction on the motion of the object.

Enter the name of the object that should be followed by the camera (you can also use the Camera Actuator for non-camera objects) into the "OB:" field. The field "Height:" determines the height above the object the camera stays at. "Min:" and "Max:" are the bounds of distance from the object to which the camera is allowed to move. The "X" and "Y" buttons specify which axis of the object the camera tries to stay behind.

Camera Actuator Python Functions
returns Function Explanation
float getHeight Returns the height value set in the height: field.
float getMax Returns the maximum value set in the Max: field.
float getMin Returns the minimum value set in the Min: field.
object or string getObject getObject(name_only = 1) name_only - optional arg, when true will return the KX_GameObject rather then its name Returns the object this sensor reacts to.
bool getXY Gets the axis the camera tries to get behind. True = X, False = Y
setHeight Sets the height value.
setMax Sets the maximum value.
setMin Sets the minimum value.
setObject setObject(object) - object: KX_GameObject, string or None Sets the object this sensor reacts to.
setXY Sets axis the camera tries to get behind. 1=x, 0=y

Sound Actuator

The Sound Actuator plays a Sound Object loaded using the Sound Buttons (see Section Sound Butttons). Use the Menu Button to browse and choose between the Sound Objects in the scene.

GameKit2 Reference 13-92 SoundActuator.png

Sound play modes (MenuBut)

Play Stop Plays the sound for as long as there is a positive event from the controller

Play End Plays the sound to the end, when a positive event is send from the controller

Loop Stop Plays and repeats the sound, as long as the controller sends a positive event

Loop End Plays the sound repeatedly, as long as the controller sends a positive event. When the events stops the sound is played to its end.

Sound Actuator Python Functions
returns Function Explanation
string getFilename() Gets the name of the sound block we play
float getGain() Gets the gain (volume) of the sound
integer getLooping() Returns the current loop mode of the actuator
float getPitch() Returns the pitch of the sound
float getRollOffFactor() Returns the roll off factor (scale for distance) for the sound
integer getType() Returns the operation mode of the actuator
pauseSound() Pause the sound
setFilename(string) Set the name of the sound block
setGain() Sets the gain (volume) of the sound
setLooping() Sets the loop mode of the actuator
setPitch() Sets the pitch of the sound
setRollOffFactor() Sets the roll off factor for the sounds
setType() Sets the operation mode of the actuator
startSound() (re)starts the sound
stopSound() stops the sound

Property Actuator

The Property Actuator is meant to assign values to properties or even calculate with properties. See the Chapter about #Reference.

With the mode-menu you can switch between the three modes of this Actuator.

GameKit2 Reference 13-93 PropertyActuator.png

Assign Assigns a value or Expression (given in the "Value" field) to a Property. For example with an Expression like "Proppy + 1" the "Assign" works like an "Add". To assign strings you need to add quotes to the string ("...").

Add Adds the value or result of an expression to a property. To subtract simply give a negative number in the "Value:" field.


GameKit2 Reference 13-94 Property Copy Actuator.png

Copy This copies a Property named "Count" from the Object "Cube" into the Property "Proppy" on the actual object. This is an easy and safe way to pass information between objects. You cannot pass information between scenes with this Actuator!

Exclamation mark.png
This Actuator provides Python functions to get and set the values and Property-names. However, from Python it is much easier to access Properties directly.


Property Actuator Python Functions
returns Function Explanation
string getProperty getProperty(name) Return the property on which the actuator operates.
depends getValue getValue() Returns the value with which the actuator operates.
setProperty setProperty(name) - name: string Set the property on which to operate. If there is no property of this name, the call is ignored.
setValue setValue(value) - value: string Set the value with which the actuator operates. If the value is not compatible with the type of the property, the subsequent action is ignored.

Edit Object Actuator

GameKit2 Reference 13-95 EditObjectTypeActuator.png

This actuator performs actions on Objects itself, like adding new objects, deleting objects, etc. By default the type of this Actuator is set to "Add Object". With the type-menu you can switch between following types:


Add Object

With this Actuator type you can add new objects to the scene. This can be new enemies, bullets, particles (numerous small objects, not Blender Particles) etc.

GameKit2 Reference 13-96 EditObjectActuator.png

The Add Object actuator adds an object to the scene. The new object is oriented along the X-axis of the creating object.

Exclamation mark.png
Keep the object you'd like to add on a separate and hidden layer. You will see an error message on the console or debug output when not following this rule and no object will appear.

Enter the name of the Object to add in the "OB:" field if the entered Object does not exist in the scene Blender will blank the input field. The "Time:" field determines how long (in frames) the object should exist. The value "0" denotes it will exist forever. Be careful not to slow down the game engine by generating too many objects! If the time an object should exist is not predictable, you can also use other events (collisions, properties, etc.) to trigger an "End Object" for the added object using Logic Bricks.

With the "linV" buttons it is possible to assign an initial velocity to the added object. This velocity is given in X, Y and Z components. The "L" button stands for local. When it is pressed the velocity is interpreted as local to the axis of the added object.

Edit Object Actuator Python Functions
returns Function Explanation
list [vx,vy,vz] GetAngularVelocity() Returns the angular velocity that will be assigned to the created object.
getLastCreatedObject() get the object handle to the last created object. This way you can manipulate dynamically added objects.
list [vx,vy,vz] getLinearVelocity() Returns the linear velocity that will be assigned to the created object.
depends getObject(name_only = 1) Returns the name of the object that will be added. name_only - optional arg, when true will return the KX_GameObject rather then its name
getTime() Returns the lifetime of the object that will be added.
instantAddObject() immediately add object without delay
setAngularVelocity(vx, vy, vz) vx: float - vy: float - vz: float - Assign this angular velocity to the created object.
setLinearVelocity(vx, vy, vz) vx: float - vy: float - vz: float Assign this velocity to the created object.
setObject(object) object: KX_GameObject, string or None Sets the object that will be added. There has to be an object of this name. If not, this function does nothing.
setTime(duration) duration: integer Sets the lifetime of the object that will be added, in frames. If the duration is negative, it is set to 0. Zero means unlimited lifetime

Examples: - AddObject.blend

End

GameKit2 Reference 13-97 EditObject End Actuator.png

This type of the Edit Object Actuator simply ends or kills the current Object. This is very useful for ending a bullet's life after a collision or something similar.


Replace Mesh

GameKit2 Reference 13-98 EditObject ReplaceMesh Actuator.png

This type of the Edit Object Actuator replaces the mesh of the object by another mesh with the given name in the "ME:" field.. The other mesh must be existent in the scene of course. Use a "Fake User" to ensure that you can't loose the mesh when working with Logic Bricks.


Motion Actuator Python Functions
returns Function Explanation
string getMesh() Returns the name of the mesh to be substituted.
instantReplaceMesh() Immediately replace mesh without delay
setMesh(name) String or None Set the mesh that will be substituted for the current one.

Track To

GameKit2 Reference 13-99 EditObject TrackTo Actuator.png

The "Track to" type, rotates the object in such a way that the Y-axis points to the target specified in the "OB:" field. Normally this happens only in the X/Y plane of the object (indicated by the "3D" button not being pressed). With "3D" pressed the tracking is done in 3D. The "Time:" parameter sets how fast the tracking is done. Zero means immediately, values above zero produce a delay (are slower) in tracking.

Track To Actuator Python Functions
returns Function Explanation
KX_GameObject or string getObject getObject(name_only = 1) name_only - optional arg, when true will return the KX_GameObject rather then its name Returns the object to track with the parent of this actuator
integer getTime getTime() - time: integer Return the time in frames with which the tracking motion is delayed.
bool getUse3D getUse3D() Returns 1 if the motion is allowed to extend in the z-direction.
setObject setObject(object) - object: KX_GameObject, string or None Set the object to track with the parent of this actuator.
setTime setTime(time) - time: integer Set the time in frames with which to delay the tracking motion.
setUse3D setUse3D(value) - value: 0 or 1 Set to 1 to allow the tracking motion to extend in the z-direction, set to 0 to lock the tracking motion to the x-y plane.

Dynamics

GameKit2 Reference 13-100 EditObject Dynamics Actuator.png

Using this type of the EditObject Actuator you can switch on and off the physical evaluation of the object carrying the Actuator. This can become handy to speed up things, e.g. disable dynamics for inactive enemies for example.


GameKit2 Reference 13-101 DynamicsType.png

Enable/Disable Dynamics switch on/off the whole physical behavior of the object.


Enable/Disable Rigid Body switch on/off the rolling or tumbling physics for the object.


Dynamics Edit Object Actuator Python Functions
returns Function Explanation
integer getOperation getOperation() -> integer Returns the operation type of this actuator.
setOperation setOperation(operation?) - operation? : type of dynamic operation 0 = restore dynamics 1 = disable dynamics 2 = enable rigid body 3 = disable rigid body Change the dynamic status of the parent object.

Scene Actuator

GameKit2 Reference 13-102 SceneActuator Types.png

The Scene Actuator is meant for switching Scenes and Cameras in the game engine or adding overlay or background scenes.

Choose the desired action with the Menu Button and enter an existing camera or scene name into the text field. If the name does not exist, the button will be blanked!

Reset Simply restarts and resets the scene. It has the same effect as stopping the game with ESC and restarting with PKEY .

Set Scene Switch to the scene indicated into the text field. Switching will reset the actual scene!

Set Camera Switch to the Camera indicated in the "OB:" text field.

Add OverlayScene Adds the overlay scene indicated in the text field "SCE:", which is rendered on top of all other (existing) scenes.

Add BackgroundScene Adds a background scene which will be rendered behind all other scenes.

Exclamation mark.png
Added Scenes with own lights will add to the light of the base scenes as well. If this is not wanted, remove the lights from the added scenes or use layered lighting.

Remove Scene Removes a scene.

Suspend Scene Suspends named ("SCE:") scene until "Resume Scene" is called. Be careful not to suspend the actual scene if there is no other scene to resume!

Resume Scene Resumes a suspended Scene.

Scene Actuator Python Functions
returns Function Explanation
string getCamera() Return the name of the camera to switch to.
string getScene() Return the name of the scene the actuator wants to switch to.
bool getUseRestart() Return whether the scene will be restarted.
setCamera(camera) - camera: string Set the camera to switch to.
setExecutePriority() None
setScene(scene) scene: string Set the name of scene the actuator will switch to.
setUseRestart(flag) flag: 0 or 1. Set flag to 1 to restart the scene.

Random Actuator

An often-needed function for games is a random value to get more variation in movements or enemy behavior.

GameKit2 Reference 13-103 RandomActuator.png

The "Seed"-parameter is the value fed into the random generator as a start value for the random number generation. Because computer generated random numbers are only "pseudo" random (they will repeat after a (long) while) you can get the same random numbers again if you choose the same Seed.

Exclamation mark.png
A seed of zero means no random at all!

Enter the name of the property you want to be filled with the random number into the "Property:" field.

Random Actuators types

Boolean Constant This is not a random function at all, use this type to test your game logic with a TRUE or FALSE value.

Boolean Uniform This is the classic random 50-50 pick. It results in TRUE or FALSE with an equal chance. This is like an (ideal) flip of a coin.

Boolean Bernoulli This random function results in a boolean value of TRUE or FALSE, but instead of having the same chance for both values you can control the chance of having a TRUE pick with the "Chance" parameter. A chance of 0.5 will be the same as "Bool Uniform". A chance of 0.1 will result in 1 out of 10 cases in a TRUE (on average).

Integer Constant For testing your logic with a value given in the "Value:" field

Integer Uniform This random type randomly produces an integer value between (and including) "Min:" and "Max:". The classical use for it is to simulate a dice pick with "Min: 1" and "Max: 6".

Integer Poisson The random numbers are distributed in such a way that an average of "Mean:" is reached with an infinite number of picks.

Float Constant For debugging your game logic with a given value.

Float Uniform This returns a random floating point value between "Min:" and "Max:".

Float Normal Returns a weighted random number around "Mean:" and with a standard deviation of "SD:".

Float Negative Exponential Returns a random number which is well suited to describe natural processes like radioactive decay or lifetimes of bacteria. The "Half-life time:" sets the average value of this distribution.

XXX Actuator Python Functions
returns Function Explanation
integer getDistribution() Returns the type of the active distribution.
depends getPara1() Returns the first parameter of the active distribution. Refer to the documentation of the generator types for the meaning of this value.
depends getPara2() Returns the first parameter of the active distribution. Refer to the documentation of the generator types for the meaning of this value.
string getProperty(name) Return the property to which the random value is assigned. If the generator and property types do not match, the assignment is ignored.
integer getSeed() Returns the initial seed of the generator. Equal seeds produce equal series.
setBoolBernouilli(value) value: a float between 0 and 1 Return false value * 100%% of the time.
setBoolConst(value) value: 0 or 1 Set this generator to produce a constant boolean value.
setBoolUniform() Set this generator to produce true and false, each with 50%% chance of occuring
setFloatConst(value) value: float Always return value
setFloatNegativeExponential(half_life) half_life: float Return negative-exponentially distributed numbers. The half-life 'time' is characterized by half_life.
setFloatNormal(mean, standard_deviation) mean: float - standard_deviation: float Return normal-distributed numbers. The average is mean, and the deviation from the mean is characterized by standard_deviation.
setFloatUniform(lower_bound, upper_bound) lower_bound: float - upper_bound: float Return a random integer between lower_bound and upper_bound.
setIntConst(value) value: integer Always return value
setIntPoisson(value) value: float Return a Poisson-distributed number. This performs a series of Bernouilli tests with parameter value. It returns the number of tries needed to achieve success.
setIntUniform(lower_bound, upper_bound) lower_bound: integer - upper_bound: integer Return a random integer between lower_bound and upper_bound. The boundaries are included.
setProperty(name) name: string Set the property to which the random value is assigned. If the generator and property types do not match, the assignment is ignored.
setSeed(seed) seed: integer Set the initial seed of the generator. Equal seeds produce equal series. If the seed is 0, the generator will produce the same value on every call.

Examples: - RandomActuator.blend

Message Actuator

GameKit2 Reference 13-104 MessageActuator.png

This LogicBrick sends a message out, which can be received and processed by the Message Sensor.

The "To:" field indicates that the message should only be sent to objects with the given name.

The subject of the message is indicated in the "Subject:" field. With these two possibilities you can control the messaging very effectively.

The body (content) of the message can either be a text ("Body:") string or the content of a Property when "T/P" is activated ("Propname:"). See Section [#MessageBody] on how to read the body of a message with a simple Python.script.

Message Actuator Python Functions
returns Function Explanation
setBody Sets the body of the message.
setBodyType Sets whether the body should be text or a Property name.
setSubject Sets the subject of the message.
setToPropName Sets the property name the message should be send to

Game Actuator

With the Game Actuator you can load new levels from disk, quit or restart a game.

GameKit2 Reference 13-105 GameActuator.png

Start: Blender, the Blenderplayer or a Blender executable will load the named file from disk and start it. To pass information between the actual and loaded level see #GameLogic.globalDict.

Restart: Restarts the current scene. All information is reset!

Quit: Quits a game. Inside Blender you will be back in the editing of the scene, in Blenderplayer or in executables you will return to operating system level. The quit function es especially important if you redefined the ESC key!

Load/Save GameLogic.globalDict: Loads/Saves the global directory to save game states. See #GameLogic.globalDict.

XXX Actuator Python Functions
returns Function Explanation
string getFile getFile() get the name of the file to start.
setFile setFile(name) set the name of the file to start.

Visibility Actuator

GameKit2 Reference 13-106 VisibilityActuator.png

This actuator allows you to make an object visible or invisible. Visible/invisible Recursive will make all child objects visible/invisible.

Exclamation mark.png
To change visibility from a Python script use the function setVisibility() from the game object (controller.getOwner().setVisible(visible,recursive)).

2D Filter Actuator

GameKit2 Reference 13-107 2DFilterActuator.png

The 2D Filter Actuator is somehow special, because it works on the whole game. You can add it to any object and the whole image (real time)-rendered will be affected.

Currently there are some simple 2d filters and the possibility to add your own shader scripts.

Built-in Filters: Motion Blur, Blur, Sharpen, Dilation, Erosion, Laplacian, Sobel, Prewitt, Gray Scale, Sepia and Invert.

Custom Filters

Custom filters give you the ability to define your own 2d filter using GLSL. Its usage is the same as built-in filters, but you must select "Custom Filter" in 2D Filter actuator, then write a shader program into the Blender Text Editor and enter the shader script name.

For more information on the OpenGL Shading Language (GLSL) see GLSL specification on opengl.org.

You can also use these uniform variables in your shader program:

Variable Usage
bgl_RenderedTexture uniform sampler2D bgl_RenderedTexture;
bgl_TextureCoordinateOffset uniform vec2 bgl_TextureCoordinateOffset[9];
bgl_TextureWidth uniform float bgl_TextureWidth;
bgl_TextureHeight uniform float bgl_TextureHeight;

Example Shader Program: Blue Sepia

uniform sampler2D bgl_RenderedTexture;
  void main(void)
  {
      vec4 texcolor = texture2D(bgl_RenderedTexture,gl_TexCoord[0].st);
      float gray = dot(texcolor.rgb,vec3(0.299, 0.587, 0.114));
      gl_FragColor = vec4(gray * vec3(0.8, 1.0, 1.2),texcolor.a);
  }

Parent Actuator

GameKit2 Reference 13-108 ParentActuator.png

The Parent Actuator sets or removes a parent relationship between two objects. The logic must be in the child object.

Set Parent: Sets a parent relationship between the object carrying the Actuator and the object named in the "OB:"-field which is then the parent (controlling object)..

Remove Parent Removes the parent relation

XXX Actuator Python Functions
returns Function Explanation
KX_GameObject or string getObject getObject(name_only = 1) name_only - optional arg, when true will return the KX_GameObject rather then its name Returns the object that is set to.
setObject setObject(object) - object: KX_GameObject, string or None, sets the object to set as parent.

Examples: - ParentActuator.blend

State Actuator

GameKit2 Reference 13-109 StateActuator.png

The State Actuator allows to set states (see [[#State Actuator])

Cpy Copies the selected states from the Actuator to the general state. This will overwrite all states with the ones set in the Actuator.
Add Add the selected states to the general state
Sub Subtract the selected states from the general state
Inv Inverting the selected states bitwise. See Examples
XXX Actuator Python Functions
returns Function Explanation
setMask(mask) mask : bits that will be modified Set the value that defines the bits that will be modified by the operation. The bits that are 1 in the value will be updated in the object state, the bits that are 0 are will be left unmodified expect for the Copy operation which copies the value to the object state.
setOperation(op) op : bit operation (0=Copy, 1=Set, 2=Clear, 3=Negate) Set the type of bit operation to be applied on object state mask. Use setMask() to specify the bits that will be modified.

Examples:

  • InvStateActuator.blend
  • StateDebug.blend

Game engine Python

Python is an interpreted, interactive, object-oriented programming language.

Python combines remarkable power with very clear syntax. It has modules, classes, exceptions, very high level dynamic data types, and dynamic typing. Python is also usable as an extension language for applications that need a programmable interface.

Beside this use as an extension language, the Python implementation is portable to (at least) all platforms that Blender runs on.

Python is copyrighted but freely usable and distributable, even for commercial use.

In Blender there are two incarnations of the Python integration: Blender Python meant for extending Blender and its modeling and animation tools and the BGE Python meant to be used with real time content.

Text Window

The Text Window is a simple but useful text editor, fully integrated into Blender. It's main purpose of it is to write Python scripts, but it is also very useful for writing comments in the Blendfile or to explain the purpose of the scene to other users.

The Text Window can be displayed with SHIFT-F11 or by adjusting the WindowType menu in the WindowHeader.

GameKit2 Reference 13-110 TextWindow.png

In the Text Window Header there is the file menu for opening, saving and executing Python scripts. In the Edit menu you can find the common functions to copy&paste, search&replace etc. The Format menu will assist you in formating the code which is especially important because Python uses the indentation to mark code blocks.

The first Icon in the Text Window Header will make the Text Window fullscreen, this can also be done with the keyboard CTRL-UP and CTRL-DOWN.

The next icon switches on the line numbers, which is very helpful for programming and debugging.

The icon right to the line number icon will enable a word wrap, good for typing longer texts in the Text Window.

The "AB" buttons enables syntax highlighting for python keywords.

The icon with the (Python-)snake on it enables the use of Python text plug ins.

The next buttons can be used to browse between text files, open new ones or add new text buffers. The "X"-shaped Button deletes a text buffer.

With the Button (labeled "Screen 15" in the figure above) on the right side you can change the font used to display the text.

You can scroll the text using the scrollbar on the left, using SHIFT-MMB and mouse movements or using the mouse wheel.

By holding LMB and then dragging the mouse you can mark ranges of text for the usual cut, copy & paste functions. The key commands are:

ALT-C Copies the marked text into a buffer

ALT-X Cuts out the marked text into a buffer

ALT-V Pastes the text from buffer to the cursor in the Text Window

ALT-O Loads a text, a FileWindow appears

CTRL-R Reloads the current text, very useful for editing with an external editor

SHIFT-ALT-F Pops up the Filemenu for the Text Window

ALT-F Find function

ALT-J Pops up a Number Button where you can specify a line number that the cursor will jump to

ALT-U Unlimited Undo for the Text Window

ALT-R Redo function, recovers the last Undo

ALT-A Marks the whole text

BGE Python

With Python integrated into the game engine you can influence Logic Bricks, change their parameters and react to events triggered by the Logic Bricks.

Besides that you can influence the GameObject that carries the Python Controller directly. This means moving it, applying forces or getting information from this object.

Exclamation mark.png
In addition to the Python in the game engine, Blender includes Python for modeling and animation tasks, which is not covered here.

Basic Blender Game Engine Python

The first step for using Blender game engine (BGE) Python is to add at least a Sensor and a Python Controller to an object. Then add a new text file in the Text Window. Fill in the name of that text file into the "Script:" field of the Python Controller. You should now have a game logic setup like in this Figure.

Logic Bricks for a first game Python script

Now enter the following script into the Text Window (you don't need to type the lines starting with "#", these are comments).


# first BGE Python script
  # gets the position of the object 
  # and prints it to the console
 
  import GameLogic
 
  cont = GameLogic.getCurrentController()
  me   = cont.getOwner()
 
  print me.getPosition()

Listing [!xxx]. First Simple Script

The result of the "print" command and errors from the Python interpreter will appear on the console from which you started Blender from, or in the DOS window, when running Blender from Windows. So it is helpful to size the Blender window in such a way that you can see the console window while programming Python.

This basic script only prints the position of the object that owns the Python Controller. Move your object and then restart the game engine with the PKEY to see the results changing, or attach a Motion Actuator to the object to move it..

Now for an explanation of the script line by line. Line five is an important line. We import the "GameLogic" module which is the basis for all game Python in Blender.

Exclamation mark.png
In fact every script executed from the game engine will import this script without the need of this line. However it is good style to import it, so one can immediately see that this is a BGE Python. Also using "import GameLogic as GL" and writing "GL.xxx" later is a nice time saver.

In line seven we ask with "getCurrentController()" for a pointer to the Controller which executes the script and do assign it to the variable "cont". You can see "getCurrentController()" is a function provided by the module "GameLogic".

In line eight we use the controller we got in line seven to get the owner, meaning the GameObject carrying the LogicBrick. You can see we use the method "getOwner()" provided by the controller to get the owner of our controller.

We now have a pointer to the owner of the Controller and we can use its methods to do things with it. Here in line 10 we use the "getPosition()" method to print the position of the GameObject as a matrix of the X, Y and Z values.

You may now wonder what other methods the PythonObjects have. Of course this is part of this documentation, but Python is "self" documenting, so we have other ways to get that information.

Add the following line to the end of the script from Figure 28-3:

print dir(owner)

Start the game engine again, stop it and look at the console window. You will see the following output:

  [0.0, 0.0, 0.0] 
  ['alignAxisToVect', 'applyImpulse', 'disableRigidBody', 'enableRigidBody', 'endObject',
  'getAngularVelocity', 'getAxisVect', 'getChildren', 'getChildrenRecursive', 'getDistanceTo',
  'getLinearVelocity', 'getMass', 'getMesh', 'getName', 'getOrientation', 'getParent', 'getPhysicsId',
  'getPosition', 'getPropertyNames', 'getReactionForce', 'getState', 'getVectTo', 'getVelocity',
  'getVisible', 'isA', 'rayCast', 'rayCastTo', 'removeParent', 'restoreDynamics',
  'setAngularVelocity', 'setCollisionMargin', 'setLinearVelocity', 'setOrientation', 'setParent',
  'setPosition', 'setState', 'setVisible', 'suspendDynamics']

The first line shows the position of the object, the next lines show the methods, that the "owner" provides. For example you see a 'getMass' method, which will return the mass of a dynamic object. With the knowledge of the "dir()" function you can ask Python objects for information, without consulting external documentation.

Examples:

  • FirstBGEPython.blend
  • FirstBGEPython1.blend

Actuator Access

The next step for our quick introduction to BGE Python is the access for Actuators. Generally it is possible to change values in the Actuators and to activate or deactivate the Actuator from within Python.

GameKit2 Reference 13-112 FirstActuator.png

Build a logic as shown in the figure above. Make sure that you enter a value for "Rot", or nothing will move in our example. Then change the python script or enter a new one as shown in the listing below.

Exclamation mark.png
It is a good style to name the Logic Bricks to make the logic clear and to avoid errors in scripts
  # BGE Python script
  # 
  # Access to the  Actuator
 
  import GameLogic
 
  cont = GameLogic.getCurrentController()
  me   = cont.getOwner()
 
  moveit = cont.getActuator("Moveit")
  GameLogic.addActiveActuator(moveit,1)

Listing [!xxx]. Actuator Access

In line 10 you can see how an Actuator is accessed. The Controller variable "cont" provides a "getActuator()" function. We pass it the name of the Actuator as string. It it possible to have numerous Actuators connected to a Controller, so a good talking name will help here to avoid confusion. The next line now uses a function from the GameLogic module "addActiveActuator()" to enable the Actuator. The parameters are first the variable holding the Actuator and a "1" to enable the Actuator. In the rare case where you need to stop an Actuator you would pass a "0".

When everything is entered correctly and the Logic Bricks are connected the right way (and named according to the script), you can press PKEY to start the game engine. The cube should now rotate. Of course this is much easier with a simple AND-Controller, but in the next step we will do something which is not possible with only Logic Bricks.

Properties and Actuators

Imagine you want to speed up an object slowly. With Logic Bricks there is no simple way to achieve this, but with some Python it is easy to do.

GameKit2 Reference 13-113 FirstActuatorProperty.png

First we add a Property (see #Properties) by clicking on the "Add Property" button left of the Logic Bricks of our small testscene. Leave the type to "Float" and name the property "speed", this Property will hold the current speed (I will use rotation speed) of our object. You should also activate the "D" button, this will show the property in the 3DView while the game is running. This is usually only done when the 3DView is not in textured mode, so check that you are in wireframe or solid mode. If you want to see the Debug output also in textured mode use the Game-menu to activate "Show Debug Properties".

Now change the existing script:


  # BGE Python script
  # 
  # Access to the  Actuator
 
  import GameLogic
 
  cont = GameLogic.getCurrentController()
  me   = cont.getOwner()
 
  moveit = cont.getActuator("Moveit")
 
  me.speed = me.speed + 0.0005
 
  moveit.setDRot(0,0,me.speed,1)
  GameLogic.addActiveActuator(moveit,1)

Listing: Properties and changing Actuators

You may have wondered what line 8 was used for in the previous script, it was just left in for convenience, but now we use the variable "me" which is holding a pointer to our object to access the Property we created in the Logic Buttons. In line 12 we add "0.0005" every time the script is called to the property "speed". This will make "speed" count up in very small steps, however, since the script gets called every 1/60th of a second it will count up quite fast.

In line 14 we now set the Rot value for the Z-axis with the "speed" value. The first three argument values to "setDRot()" are the rotation around X, Y and Z. The fourth argument denotes if the rotation should be around the local axis ("1") or global axis ("0"). This is the Python counterpart to the "L" button in the Motion Actuator.

Sensor Access

For completeness I will now demonstrate how to access a sensor from Pyton.


  # BGE Python script
  # 
  # Access to the  Actuator
 
  import GameLogic
 
  cont = GameLogic.getCurrentController()
  me   = cont.getOwner()
 
  moveit = cont.getActuator("Moveit")
  always = cont.getSensor("Always")
 
  if always.isPositive():
  	me.speed = me.speed + 0.0005
 
  	moveit.setDRot(0,0,me.speed,1)
  	GameLogic.addActiveActuator(moveit,1)

Listing [!xxx]. Sensor Access

This looks very similar like the Actuator Access. In line 11 we get a pointer to the Sensor named "Always" into a variable and can now use its functions. Here we just use "isPositive()" which will only return "true" if the Sensor fires a positive event. In this case it is again just for demonstrating and will not provide extra functionality. But in the case of other sensor types or the case that there are more sensors connected to the Python-Controller this function will help us very much.

See the file "FirstBGEPython6.blend" for an example with two KeyboardSensors controlling the rotational speed of the object.

GameLogic Module

The GameLogic module is the base of all game logic by Python.

GameLogicModule
returns Function Explanation
addActiveActuator addActiveActuator(actuator,bool)
string expandPath(path) Converts a blender internal path into a proper file system path. path - the string path to convert. Use / as directory separator in path You can use '//' at the start of the string to define a relative path; Blender replaces that string by the directory of the startup .blend or runtime file to make a full path name (doesn't change during the game, even if you load other .blend). The function also converts the directory separator to the local file system format.
int getAverageFrameRate() Gets the estimated average frame rate
list getBlendFileList(path) Gets a list of blend files in the same directory as the current blend file or the list from "path"
controller getCurrentController() gets the current controller (the one "owning" the script)
scene getCurrentScene() getCurrentScene() Gets a reference to the current scene.
integer getLogicTicRate() Gets the logic tic rate
integer getPhysicsTicRate() Gets the physics tic rate
float getRandomFloat() returns a random floating point value in the range [0..1)
dict globalDict() dict() -> new empty dictionary. dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs. dict(seq) -> new dictionary initialized as if via: d = {} for k, v in seq: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)
setGravity(x,y,z) set Gravitation
setLogicTicRate() Sets the logic tic rate
setPhysicsTicRate() Sets the physics tic rate

Rasterizer Module

Module
returns Function Explanation
disableMotionBlur() disable motion blur
enableMotionBlur() enable motion blur
enableVisibility() enable visibility
float getEyeSeparation() get the eye separation for stereo mode
float getFocalLength() get the focal length for stereo mode
string getGLSLMaterialSetting(string) get the state of a GLSL material setting
getMaterialMode() get the material mode being used for OpenGL rendering
integer getWindowHeight() get window height (see Trackball.blend)
integer getWindowWidth() get window width
makeScreenshot(path) make screenshot, saved in format as denoted in the Display Buttons
setAmbientColor("[r,g,b,a]") set Ambient Color
setBackgroundColor("[r,g,b,a]") set Background Color
setEyeSeparation(float) set the eye separation for stereo mode
setFocalLength(float) set the focal length for stereo mode
setGLSLMaterialSetting() set the state of a GLSL material setting
setMaterialMode() set the material mode to use for OpenGL rendering
setMistColor() set Mist Color (rgb)
setMistEnd() set Mist End(rgb)
setMistStart() set Mist Start(rgb)
setMousePosition(x,y) set mouse position
showMouse(bool) show mouse in game engine mode

GameLogic.globalDict

This is a place where data can be stored even when new blend files are loaded. This was developed for Apricot, so Frankie can go into levels in new blendfiles keeping his inventory.

The GameLogic.globalDict is a Python directory, dictionaries are sometimes found in other languages as ``associative memories or ``associative arrays. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type

Here is a small example using a dictionary (from the official Python documentation at [3]):

  >>> tel = {'jack': 4098, 'sape': 4139}
  >>> tel['guido'] = 4127
  >>> tel
  {'sape': 4139, 'guido': 4127, 'jack': 4098}
  >>> tel['jack']
  4098
  >>> del tel['sape']
  >>> tel['irv'] = 4127
  >>> tel
  {'guido': 4127, 'irv': 4127, 'jack': 4098}
  >>> tel.keys()
  ['guido', 'irv', 'jack']
  >>> tel.has_key('guido')
  True
  >>> 'guido' in tel
  True

Loading and saving the GameLogic.globalDict can be done with the Game Actuator. You can access the global data with Python like this:

  # Save data before changing levels
  # gets data from a Property to globalDict
  GameLogic.globalDict['SavedScore'] = me.actualscore

Don't forget a "Save GameLogic.globalDict" with the Game Actuator before changing levels. In the new level we now have to do "Load GameLogic.globalDict" with the Game Actuator an can then access the saved data:

  # load data after loading a level
  # gets data from globalDict to a Property
  me.actualscore = GameLogic.globalDict['SavedScore']

Examples:

  • GlobalDict_L1.blend (press A to "score", loads the next level at score=5 and the score is keept in Level 2)
  • GlobalDict_L2.blend (Level 2)

GameKeys Module

This module holds key constants for the Keyboard Sensor.

PhysicsConstraints Module

This python module, PhysicsConstraints, gives access to internal physics settings that influence quality of the rigid body dynamics

createConstraint (Edge Constraint)
createConstraint( obj1_PhysicsID, obj2_PhysicsID, constraintType, edgePos_x, edgePos_y, edgePos_z, edgeAngle_x, edgeAngle_y, edgeAngle_z ) obj1_PhysicsID: integer (The physics ID of object 1) obj2_PhysicsID: integer (The physics ID of object 2) constraintType: integer 0 = No constraint. 1 = Point constraint. 2 = Edge constraint. 11 = Vehicle constraint edgePos_x: float (Blender unit) edgePos_y: float (Blender unit) edgePos_z: float (Blender unit) edgeAngle_x: float (Range: -1.0 to 1.0) edgeAngle_y: float (Range: -1.0 to 1.0) edgeAngle_z: float (Range: -1.0 to 1.0)
Exclamation mark.png
Position (edgePos_x, edgePos_y, edgePos_z) Where do you want the center of the edge to be located? (Distance from obj1's object center)
Exclamation mark.png
Angle (edgeAngle_x, edgeAngle_y, edgeAngle_z) In what direction do you want the edge to point? (Uses obj1's axis)

Sample Code:

  # import PhysicConstraints Module
  import PhysicsConstraints
 
  # get object list
  objList = GameLogic.getCurrentScene().getObjectList()
 
  # get object named Obj_1
  obj1 = objList["OBObj_1"]
 
  # get object named Obj_2
  obj2 = objList["OBObj_2"]
 
  # want to use Edge constraint type
  constraintType = 2
 
  # get Obj_1 physics ID
  obj1_ID = obj1.getPhysicsId()
 
  # get Obj_2 physics ID
  obj2_ID = obj2.getPhysicsId()
 
  # Use bottom right edge of 0bj_1 for hinge position
  edgePos_x = 1.0
  edgePos_y = 0.0
  edgePos_z = -1.0
 
  # use Obj_1 y axis for angle to point hinge
  edgeAngle_x = 0.0
  edgeAngle_y = 1.0
  edgeAngle_z = 0.0
 
  # create an edge constraint
  PhysicsConstraints.createConstraint( obj1_ID, obj2_ID,
       constraintType,
       edgePos_x, edgePos_y, edgePos_z,
       edgeAngle_x, edgeAngle_y, edgeAngle_z )

Example:

  • EdgeConstraint.blend
createConstraint (Point Constraint)
createConstraint( obj1_PhysicsID, obj2_PhysicsID, constraintType, pointPos_x, pointPos_y, pointPos_z) obj1_PhysicsID: integer (The physics ID of object 1) obj2_PhysicsID: integer (The physics ID of object 2) constraintType: integer 0 = No constraint. 1 = Point constraint. 2 = Edge constraint. 11 = Vehicle constraint pointPos_x: float (Blender unit) pointPos_y: float (Blender unit) pointPos_z: float (Blender unit)
Exclamation mark.png
Point Position (pointPos_x, pointPos_y, pointPos_z)
Exclamation mark.png
Where do you want the pivot point to be located? (Distance from obj1's object center)

Sample Code:

  # import PhysicConstraints Module
  import PhysicsConstraints
 
  # get object list
  objList = GameLogic.getCurrentScene().getObjectList()
 
  # get object named Obj_1
  obj1 = objList["OBObj_1"]
 
  # get object named Obj_2
  obj2 = objList["OBObj_2"]
 
  # want to use point constraint type
  constraintType = 1
 
  # get Obj_1 physics ID
  obj1_ID = obj1.getPhysicsId()
 
  # get Obj_2 physics ID
  obj2_ID = obj2.getPhysicsId()
 
  # Use bottom right front corner of obj1 for point position
  pointPos_x = 1.0
  pointPos_y = -1.0
  pointPos_z = -1.0
 
  # create a point constraint
  PhysicsConstraints.createConstraint( obj1_ID, obj2_ID,
       constraintType,
       pointPos_x, pointPos_y, pointPos_z)

Example blend: PointConstraint.blend

createConstraint (Vehicle Constraint)
createConstraint(obj1_PhysicsID, obj2_PhysicsID, constraintType ) obj1_PhysicsID: integer (The physics ID of the vehicle) obj2_PhysicsID: integer (Set this to zero) constraintType: integer 0 = No constraint. 1 = Point constraint. 2 = Edge constraint. 11 = Vehicle constraint.

Sample Code:

  # import PhysicConstraints Module
  import PhysicsConstraints
 
  # get object list
  objList = GameLogic.getCurrentScene().getObjectList()
 
  # get object named Car
  objCar = objList["OBCar"]
 
  # want to use vehicle constraint type
  constraintType = 11
 
  # get car physics ID
  carID = objCar.getPhysicsId()
 
  # create a vehicle constraint
  PhysicsConstraints.createConstraint( carID, 0, constraintType)

Example blend: VehicleConstraint.blend

getAppliedImpulse
getAppliedImpulse(constraintId) Returns the applied impulse. Return type: float constraintId: integer
Exclamation mark.png
Save the constraintID when the constraint is created.

Sample Code:

1st script

  # import PhysicConstraints Module
  import PhysicsConstraints
 
  # get object list
  objList = GameLogic.getCurrentScene().getObjectList()
 
  # get object named Car
  objCar = objList["OBCar"]
 
  # want to use vehicle constraint type
  constraintType = 11
 
  # get car physics ID
  car_ID = objCar.getPhysicsId()
 
  # create a vehicle constraint
  carConst = PhysicsConstraints.createConstraint( car_ID, 0, constraintType)
 
  # get the constraint ID
  carConst_ID = carConst.getConstraintId()                                   
 
  # save the constraint ID as a objCar variable
  objCar.constraint_ID = carConst_ID
 
  #### rest of script

2nd script

  # import PhysicConstraints Module
  import PhysicsConstraints
 
  # get object list
  objList = GameLogic.getCurrentScene().getObjectList()
 
  # get object named Car
  objCar = objList["OBCar"]
 
  # get car constraint ID that was saved
  carConst_ID = objCar.constraint_ID
 
  # get the applied impulse
  appliedImpulse = PhysicsConstraints.getAppliedImpulse(carConst_ID)
getVehicleConstraint
getVehicleConstraint(constraint_ID) Returns the vehicle constraint ID. constraint_ID: integer

Sample Code:

  # import PhysicConstraints Module
  import PhysicsConstraints
 
  # get object list
  objList = GameLogic.getCurrentScene().getObjectList()
 
  # get object named Car
  objCar = objList["OBCar"]
 
  # want to use vehicle constraint type
  constraintType = 11
 
  # get car physics ID
  car_ID = objCar.getPhysicsId()
 
  # create a vehicle constraint
  carConst = PhysicsConstraints.createConstraint( car_ID, 0, constraintType)
 
  # get the constraint ID
  carConst_ID = carConst.getConstraintId() 
 
  # get vehicle constraint
  car = PhysicsConstraints.getVehicleConstraint(carConst_ID)
removeConstraint
removeConstraint(constraint_ID) Removes the constraint. constraint_ID: integer
Exclamation mark.png
Save the constraintID when the constraint is created.
Exclamation mark.png
This removes the constraint between 2 game objects (point and edge constraints). It does not remove vehicle constraints.

Sample Code:

Part 1: Create a Point Constraint

  #########  PointConstraint.py
 
  # import PhysicConstraints Module
  import PhysicsConstraints
 
  # get object list
  objList = GameLogic.getCurrentScene().getObjectList()
 
  # get object named Obj_1
  obj1 = objList["OBObj_1"]
 
  # get object named Obj_2
  obj2 = objList["OBObj_2"]
 
  # want to use point constraint type
  constraintType = 1
 
  # get Obj_1 physics ID
  obj1_ID = obj1.getPhysicsId()
 
  # get Obj_2 physics ID
  obj2_ID = obj2.getPhysicsId()
 
  # Use bottom right front corner of obj1 for point position
  pointPos_x = 1.0
  pointPos_y = -1.0
  pointPos_z = -1.0
 
  # create a point constraint
  constraint = PhysicsConstraints.createConstraint( obj1_ID, obj2_ID,
       constraintType,
       pointPos_x, pointPos_y, pointPos_z)
 
  # get the constraint ID
  constraint_ID = constraint.getConstraintId()
 
  # save the constraint ID as an Obj_1 variable
  obj1.constraint_ID = constraint_ID

Part 2: Remove constraint script

  ###########  RemoveConstraint.py
 
  # import PhysicConstraints Module
  import PhysicsConstraints
 
  # get object list
  objList = GameLogic.getCurrentScene().getObjectList()
 
  # get object 1
  obj1 = objList["OBObj_1"]
 
  # get constraint ID that was saved as an Obj_1 variable
  # when the constraint was created
  constraint_ID = obj1.constraint_ID
 
  # remove constraint
  PhysicsConstraints.removeConstraint(constraint_ID)

Example blend: RemoveConstraint.blend

setDeactivationTime
setDeactivationTime(time) Time (in seconds) after objects with velocity less then thresholds (see below) are deactivated time: float
Exclamation mark.png
This affects every object in the scene, except for game objects that have 'No sleeping' turned on.

Sample Code:

  # import PhysicConstraints Module
  import PhysicsConstraints
 
  # set the deactivation time
  PhysicsConstraints.setDeactivationTime(1.0)
setDeactivationLinearTreshold
setDeactivationLinearTreshold(linearTreshold) Sets the linear velocity that an object must be below before the deactivation timer can start. linearTreshold: float
Exclamation mark.png
This affects every object in the scene, except for game objects that have 'No sleeping' turned on.

Sample Code:

  # import PhysicConstraints Module
  import PhysicsConstraints
 
  # set the deactivation linear velocity threshold
  PhysicsConstraints.setDeactivationLinearTreshold(1.0)
setDeactivationAngularTreshold
setDeactivationAngularTreshold(angularTreshold) Sets the angular velocity that an object must be below before the deactivation timer can start. angularTreshold: float
Exclamation mark.png
This affects every object in the scene, except for game objects that have 'No sleeping' turned on.

Sample Code:

  # import PhysicConstraints Module
  import PhysicsConstraints
 
  # set the deactivation angular velocity threshold
  PhysicsConstraints.setDeactivationAngularTreshold(1.0)
setGravity
setGravity(gx, gy, gz) Sets the gravity for the scene. gx: float (force of gravity on world x axis) gy: float (force of gravity on world y axis) gz: float (force of gravity on world z axis)
Exclamation mark.png
This affects every object in the scene that has physics enabled.

Sample Code:

  # import PhysicConstraints Module
  import PhysicsConstraints
 
  # Beam me up!!
  # set gravity to a +10.0 on z axis
  PhysicsConstraints.setGravity( 0.0, 0.0, 10.0)

Example blend: SetGravity.blend

setLinearAirDamping
setLinearAirDamping(damping) Sets the linear air resistance for all objects in the scene. damping: float Sample Code:
# import PhysicConstraints Module
  import PhysicsConstraints
 
  # set linear air resistance to 30.0
  PhysicsConstraints.setLinearAirDamping(30.0)
setNumIterations
setNumIterations(numIter) Sets the number of times an iterative constraint solver is repeated. Increasing the number of iterations improves the constraint solver. It will descrease performance. numIter: integer Sample Code:
# import PhysicConstraints Module
  import PhysicsConstraints
 
  # repeat iterative solvers 10 times
  PhysicsConstraints.setNumIterations(10)
setNumTimeSubSteps
setNumTimeSubSteps(numSubStep) Increasing the number of time substeps improves the quality of the entire physics simulation, including collision detection and constraint solver. It will decrease performance. Set the number of timesubsteps to 0 to suspend simulation numSubStep: integer

Sample Code:

  # import PhysicConstraints Module
  import PhysicsConstraints
 
  # set time sub steps to 2
  PhysicsConstraints.setNumTimeSubSteps(2)

Message Body

One of the most asked things with the messaging system in Blender is how to get the message body. In the Message Actuator we can send a text or the content of a Property but there is no function to retrieve this with Logic Bricks.

So here we need a small script.


  # The message sensor has to be named "message"
  # body will go in existing Property "mbody"
  # The message body will be converted to the type of the Property
 
  # Only the last (if there are more than one messages send)
  # body will be stored!
 
  from types import *
 
  cont = GameLogic.getCurrentController()
  mess = cont.getSensor("message")
  me   = cont.getOwner()
 
  if mess.isPositive():
  	bodies = mess.getBodies()
  	if bodies!=None:
  		for body in bodies:
  			if type(me.mbody) is StringType:
  				me.mbody = body
  			else:
  				me.mbody = float(body)

Simple script to get the message body

This needs to be connected to a Message Sensor called "message". Fill in the Subject field as needed. However, this simple script will not work properly if more than one message arrives in one frame. All but the last message will be discarded. See the score counting mechanism in the pinball tutorial files how to avoid this.

Example:

  • MessageBody.blend
  • See also in the Pinball Tutorial files



Contents