Blender - Python Scripting
Blender - Python Scripting
gameBlender Documentation: Last modied 01/04/13 14:53:38 cw by Carsten "Calli" Wartmann V0.99b ;-) for Blender 2.12 Edition Copyright 2000, 2001 by Not a Number BV, Amsterdam
Table of Contents
1. Introduction..................................................................................................................................... 9 1.1. Intention of this document ................................................................................................... 9 1.2. Thanks & credits .................................................................................................................. 9 1.3. Why gameBlender, what are the strengths ? ...................................................................... 10 1.4. Simple gameLogic Tutorial................................................................................................ 10 2. The gameEngine............................................................................................................................ 17 2.1. Blenders gameEngine "Ketsji"........................................................................................... 17 2.2. Options for the gameEngine............................................................................................... 17 2.3. Command line options for the gameEngine....................................................................... 18 2.4. The RealtimeButtons.......................................................................................................... 20 2.5. Properties ........................................................................................................................... 22 2.6. Settings in the MaterialButtons.......................................................................................... 23 2.6.1. Specularity settings for the gameEngine ............................................................... 24 2.7. Lamps in the gameEngine.................................................................................................. 25 2.8. The blender laws of physics............................................................................................... 26 2.9. Expressions ........................................................................................................................ 27 2.10. SoundButtons ................................................................................................................... 29 2.11. SoundWindow .................................................................................................................. 30 2.12. Performance and design style issues ................................................................................ 31 3. Game LogicBricks ........................................................................................................................ 33 3.1. Sensors ............................................................................................................................... 33 3.1.1. Always Sensor ....................................................................................................... 33 3.1.2. Keyboard Sensor.................................................................................................... 34 3.1.3. Mouse Sensor ........................................................................................................ 36 3.1.4. Touch Sensor ......................................................................................................... 36 3.1.5. Collison Sensor...................................................................................................... 37 3.1.6. Near Sensor ........................................................................................................... 38 3.1.7. Radar Sensor.......................................................................................................... 39 3.1.8. Property Sensor ..................................................................................................... 40 3.1.9. Random Sensor...................................................................................................... 42 3.1.10. Ray Sensor........................................................................................................... 42 3.2. Controllers.......................................................................................................................... 43 3.2.1. AND Controller ..................................................................................................... 44 3.2.2. OR Controller ........................................................................................................ 44 3.2.3. Expression Controller............................................................................................ 44 3.2.4. Python Controller .................................................................................................. 45 3.3. Actuators ............................................................................................................................ 46 3.3.1. Motion Actuator .................................................................................................... 46 3.3.2. Constraint Actuator ............................................................................................... 48 3.3.3. IPO Actuator.......................................................................................................... 50 3.3.4. Camera Actuator.................................................................................................... 51
3.3.5. Sound Actuator...................................................................................................... 52 3.3.6. Property Actuator .................................................................................................. 53 3.3.7. Edit Object Actuator.............................................................................................. 54 3.3.8. Scene Actuator....................................................................................................... 57 3.3.9. Random Actuator................................................................................................... 59 4. UV Texturing................................................................................................................................. 63 4.1. Avaible le formats ............................................................................................................ 63 4.2. Handling of resources ........................................................................................................ 63 4.3. The UV Editor.................................................................................................................... 65 4.3.1. The ImageWindow ................................................................................................ 65 4.3.2. The Paint/FaceButtons........................................................................................... 67 4.3.3. Bitmap text in the game engine ............................................................................. 69 5. Python ............................................................................................................................................ 71 5.1. The TextWindow ................................................................................................................ 71 5.2. Python for games................................................................................................................ 72 5.2.1. Basic gamePython ................................................................................................. 73 5.3. Examples for gamePython ................................................................................................. 74 5.3.1. Moving objects with python .................................................................................. 74 5.3.2. Simple visibility check .......................................................................................... 76 5.3.3. Mouse cursor with python ..................................................................................... 77 5.4. gamePython Documentation per module ........................................................................... 78 5.4.1. GameLogic Module............................................................................................... 78 5.4.2. Rasterizer Module ................................................................................................. 79 5.4.3. GameKeys Module ................................................................................................ 80 5.5. Standard methods for LogicBricks .................................................................................... 80 5.5.1. Standard methods for Sensors ............................................................................... 80 5.5.2. Standard methods for Controllers.......................................................................... 81 5.5.3. Standard methods for gameObjects....................................................................... 82 Index................................................................................................................................................... 85
List of Tables
2-1. Valid expressions ......................................................................................................................... 28 2-2. Arithmetic expressions ................................................................................................................ 28 2-3. Boolean operations ...................................................................................................................... 28 2-4. Expression examples ................................................................................................................... 29
List of Figures
1-1. Our Player.................................................................................................................................... 11 1-2. The loaded start scene ................................................................................................................. 11 1-3. Object attributes to set ................................................................................................................. 12 1-4. LogicBricks to move our player forward .................................................................................... 13 1-5. Changing the LogicBrick type .................................................................................................... 13 1-6. LogicBricks to steer the player.................................................................................................... 15 1-7. Jump! ........................................................................................................................................... 15 2-1. The GameMenu........................................................................................................................... 17 2-2. Blender command line options.................................................................................................... 18 2-3. RealtimeButtons left part............................................................................................................. 20 2-4. Example of some LogicBricks .................................................................................................... 22 2-5. Dening properties ...................................................................................................................... 22 2-6. Material settings for dynamic objects ......................................................................................... 24 2-7. Specularity settings...................................................................................................................... 25 2-8. LampButtons, settings for gameBlender ..................................................................................... 25 2-9. The SoundButtons ....................................................................................................................... 29 2-10. 3D sound demo.......................................................................................................................... 30 2-11. The SoundWindow .................................................................................................................... 31 3-1. Common elements for Sensors.................................................................................................... 33 3-2. Pulse Mode Buttons..................................................................................................................... 34 3-4. Schematic of pulses for a near sensor ......................................................................................... 38 4-1. The ToolsMenu............................................................................................................................ 64 4-3. The Image Window ..................................................................................................................... 65 4-4. The Paint/FaceButtons................................................................................................................. 67 4-5. The special menu for the FaceSelectMode.................................................................................. 67 5-1. The TextWindow ......................................................................................................................... 71 5-2. LogicBricks for a rst gamePython script................................................................................... 73 5-3. First Script ................................................................................................................................... 73 5-4. Brownian movement.................................................................................................................... 75 5-5. Move script.................................................................................................................................. 75 5-6. LogicBricks for the brownian movement.................................................................................... 76 5-7. Visibility Script............................................................................................................................ 76 5-8. LogicBricks for the visibility script............................................................................................. 77 5-9. Mouse cursor script ..................................................................................................................... 77
Chapter 1. Introduction
1.1. Intention of this document
This document is in its current state a draft and needs input from the developers, content and the users. Mail [email protected] (mailto:[email protected]) for suggestions, error reports, critics, etc. Please dont complain when you print the PDF and next week we update the documentation. Save some trees and read it on screen until it is (more) nished.
This document is intended to provide reference documentation to the 3D-realtime part of Blender, known and referred in this document as gameBlender. It does not contain bigger tutorials, that will be part of coming documentation. It includes small demo les and examples, to show the functions in a working Blendle. This document is avaible in PDF (Portable Document Format, *.pdf) (print/gBlenderDoc.pdf.gz) and as well structured HTML with TOC and index at http://www.blender.nl/gameBlenderDoc/
Warning 2 Please take care with the Python parts, they are not 100% ready or tested (in terms of documentation!). So if you have problems dont hesitate to mail me! [email protected] (mailto:[email protected])
Chapter 1. Introduction
Erwin Coumans
Ketsji gameEngine, game logic, scripting & graphics You can read an interview for the Community Journal with Erwin here: Interview with Erwin (http://www.blender.nl/showitem.php?id=90)
Janco Verduin
3D sound for the gameEngine
Integrated environment, with modeling, animation and game player. Build-in Physics (rigid body dynamics) and Collision simulation Easy Interactivity with predened Sensors and other Logic Bricks Powerful scripting language Python for more advanced game play control True Multiplatform, All avors of Windows, Linux, FreeBSD, BeOS, Irix and more
10
Chapter 1. Introduction
To set object attributes To add LogicBricks To connect LogicBricks Basic use of the Keyboard, Always and Touch Sensor
You will not learn here how to use Blender as modelling or animation tool. For this information please refer to our online help (http://www.blender.nl/help/beginners.php) and our printed documentation (http://www.blender.nl/shop/).
Preparings
Start Blender and load the prepared start scene B-Man1.blend (blends/simple/B-Man1.blend). You can use the F1KEY or the lemenu to load a scene. After loading you should see a scene like in Figure 1-2.
11
Chapter 1. Introduction
The left 3DWindow is a textured view from the camera. The right window is a wire frame side view of the player character. It has the axis made visible and is selected, indicated by the pink color of the wire frames. The broad lower window are the RealtimeButtons, you can call then with F8. Here most of the work for interactive realtime 3D graphics in Blender will take place. Now we can start the gameEngine moving the mouse cursor to the textured 3DWindow and press PKEY. Because we have not dened any interactivity you will only see the helper lines dissappear and the sky becomming blue instead of grey. Press ESC to stop the gameEngine again.
12
Chapter 1. Introduction
Now we can run the gameEngine again. Press PKEY with the mouse over the textured view and you will see that the player falls to the oor and bounces a few times until he gets to rest. Press ESC to stop the gameEngine.
Make it move
The RealtimeButtons (F8) are logically divided into four columns. The leftmost we already used to set up the object parameters to make it fall. The three right columns are used for building the interactivity into our game. Now lets move the player on our request. Figure 1-4. LogicBricks to move our player forward
The three parts are labeled as "Sensors", "Controllers" and "Actuators". You can think of Sensors as the senses of a life form, the Controllers are the brain and the Actuators are the muscles. Now press the "Add" button for each row one time with the left mouse button to make one LogicBrick for the Sensors, Controllers and Actuators. Figure 1-5. Changing the LogicBrick type
13
Chapter 1. Introduction
The types of the added LogicBricks are nearly correct, for our rst task, only the rst one needs a change. Press and hold the MenuButton now labeled with "Always" and choose "Keyboard from the pop-up menu (see Figure 1-5). Now click with the left mouse into the "Key" eld. The text "Press any key" appears. Press the key you want to use to move the player forward (I suggest UPARROW). Now have a closer look at the Motion Controller. We will now dene how the player should move. The rst line of numbers labeled "Force" denes how much force will be applied when the Motion Controller is active. The three numbers stand for the forces in X, Y, and Z-Axis. If you look at the wire frame view of the player you see that the X-Axis is pointing forward on the player. To move forward we need to apply a positive force alon the X-Axis. To do so click and hold on the rst number in the "Force" row with the left mouse. Drag the mouse to the right to increment the value to 10.00. You can hold the CTRL key to snap the values to decadic values. Another way to enter an exact value is to hold SHIFT while clicking the eld with the left mouse. This allows you to enter a value using the keyboard. We have now nearly the conguration shown in Figure 1-4. We now need to "wire" or connect the LogicBricks. Click and hold the with the left mouse button on the yellow ball attached on the Keyboard Sensor and drag the appearing line to the yellow ring on the AND Controller. Release the mouse and the LogicBricks are connected. Now connect the yellow ball on the right side of the AND Controller with the ring on the Motion Controller. To delete a connection move the mouse over the connection. The line is now drawn highlighted and can be deleted with a XKEY or DEL keypress. Now press PKEY to start the gameEngine and when you press the UPARROW key, the player moves towards the camera.
14
Chapter 1. Introduction
More control
Figure 1-6. LogicBricks to steer the player
Now add more LogicBricks like shown in Figure 1-6. These LogicBricks will allow you to steer your player with the Cursorkeys. Note that we use the "Torque" row from the Motion Actuator to turn the player.
Jump!
To add some more degrees of freedom and to show more than one sensor as input for a Controller, we will now make the player jump. Figure 1-7. Jump!
15
Chapter 1. Introduction
Add the LogicBricks shown in Figure 1-7 to the player. The jump is triggered by a Keyboard Sensor. But there is also a Touch Sensor connected to the same AND Controller. The Touch Controller only gives an impulse when the object touches something. This constellation now reads as: " AKEY is pressed AND the player touches the ground, THEN give an impulse to the Motion Actuator". This way we make sure that you cant jump while you are in the air. Try to delete the link from the Touch Sensor to the AND Controller and see what happens... The Controller for the jumping is connected to two Motion Controllers, both have a force of 100.00 for the Z-Axis. Because 100.0 is the maximum for one Motion Actuator we simply use two Actuators to make the jump high enough. Get the complete scene here: B-Man6.blend (blends/simple/B-Man1.blend).
16
Ketsji is the name of the gameEngine. Technically the gameEngine is a framework with a collection of modules for interactive purposes like physics, graphics, logic, sound and networking. Functionally the gameEngine processes virtual reality, consisting of content (the world, its buildings) and behaviors (like physics, animation and logic). Elements in this world - also called GameObjects - behave autonomous by having a set of tools called LogicBricks, and Properties. For comparision the Properties reect memory, the Sensors are the senses, the Controllers are the brain and the Actuators allow for actions to 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.
17
With this menu you can change options during editing of your scene. Currently only the "Autostart" option is saved with the le.
18
-s <frame> -e <frame> -a
Set start to frame <frame> (use with -a) Set end to frame (use with -a)<frame> Render animation
Animation options: -a <file(s)> Playback <file(s)> -m Read from disk (Dont buffer) Window options: -w Force opening with borders -p <sx> <sy> <w> <h> Open with lower left corner at <sx>, <sy> and width and height <w>, <h> Game -g -g -g -g -g Engine specific options: fixedtime Run on 50 hertz without dropping frames vertexarrays Use Vertex Arrays for rendering (usually faster) noaudio No audio in Game Engine nomipmap No Texture Mipmapping linearmipmap Linear Texture Mipmapping instead of Nearest (default)
Turn debugging on Disable audio on systems that support audio Print this help text Disable OnLoad scene scripts, use -Y to find out why its -y
19
The word "games" is here used for all kinds of interactive 3D-content; Blender is not limited to make and play games
The RealtimeButtons can be logically 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 can also dene if an object should be calculated with the build-in physics, as an actor or should be handled as object forming the level (props on a stage).
20
Ghost Ghost objects that dont resitute to collisions, but still trigger a collision sensor. Dynamic With this option activated, the object follows the laws of physics. This option spawns new buttons that allow you to dene the objects attributes in more detail. Rigid Body The "Rigid Body" button enables advanced physics by the gameEngine. This makes it possible to make spheres roll automatically when they make contact with other objects and the friction between the materials is non-zero. The rigid body dynamics are a range of future changes to the gameEngine. Do Fh This button activates the Fh mechanism (see Section 2.6). With this option you can create a oating or swimming behaivior for actors. Rot Fh With this option set the object is rotated in such a way that the z-axis points away from the ground when using the Fh mechanism. Mass The mass of a dynamic actor has an effect on how the actor reacts when forces are applied to it. You need bigger force to move a heavier object. Note that heavier objects dont fall faster! It is the air drag that causes a difference in 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. Size The size of the bounding sphere. The bounding sphere determines the area with which collisions can occour. In future versions this will not be limited to spheres anymore. Damp General (movement) damping for the object. Use this value for simulating the damping an object recieves 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. Anisotropic When an actor moves on a surface you can dene a friction between the objects. Friction will slow down objects, because it is a force that works against any existing forces in the direction of the surface. It is controlled in the dynamic material settings (MaterialButtons F5, see Section 2.6). This friction works equally in all directions of movement.
21
With the "Anisotropic" option activated you can control the friction independently for the three axes. This is very helpful for racing games, where for example the car recieves little friction in driving direction (because of the rolling tires) and high friction sliding to the side (Example le: blends/AnisotropicFriction.blend).
Below the object settings you dene 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 (see Section 2.5). The right part of the RealtimeButtons is the command center for adding gamelogic to your objects and worlds. The logic consists of the Sensors, Controllers and Actuators. Figure 2-4. Example of some LogicBricks
Sensors are like the senses of a life form; they react on keypresses, 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 much like the mind or brain of a life form. Simple Controllers just do an AND. An example is to test if a key is pressed AND a certain time has passed. There are also OR Controllers and you also can use Python scripting and expressions in the Expression Controller to create more complex behavior. The Actuator actually perform 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 predened animations (via IPOs), which can be compared to a reex. The logic is connected (wired) with the mouse, Sensors to Controllers and Controllers to Actuators. After that you are immediately able to play the game! If you discover something in the game you dont like, just stop the gameEngine, edit your 3D world and restart. This way you can drastically cut down your dvelopement time!
2.5. Properties
Properties carry information bound to the object, similar 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 Section 3.3.6).
22
The big "ADD property" button adds a new Property. By default a Property of the oat type is added. Delete a Property with its "Del" button. The MenuButton denes the type of the Property. Click and hold it with the left mouse button and choose from the popup menu. The "Name:" text eld can be edited by clicking it with the left mouse button. SHIFT-BACKSPACE clears the name.
Property names are case sensitive. So "Erwin" is not equal to "erwin".
The next eld is different for each of the Property types. For the boolean type there are two radiobuttons; choose between "True" and "False". The string-type accepts a string; enter a string by clicking in the eld with the left mouse. The other types are using a NumberButton to dene 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 capital 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 oating point number. String Stores a text string. You can also use Expressions or the Property Sensor to compare strings. Timer This Property type is updated with the actual game time in seconds, starting from zero. On newly created object the timer starts when the object is "born".
23
Restitut This parameter controls the elasticity of collisions. A value of 1.0 will convert all the kinetic energy of the object to the opposite force. This object then has an ideal elasticity. This means that if the other object (i.e. the ground) also has a Restitut of 1.0 the object will keep bouncing forever. Friction This value controls the friction of the objects material. If the friction is low, your object will slide like on ice, with a high friction you get an effect like sticking in glue. Fh Force In conjunction with the "Do Fh" and/or "Rot Fh" (see Section 2.4) you make an object oat above a surface. "Fh Force" controls the force that keeps the object above the oor.
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 (see the example: FhDemo.blend (blends/FhDemo.blend)).
24
Lamps are created with the Toolbox (SPACE->ADD Lamp). For a selected lamp you can switch to the LampButtons (F4) to change the properties of that lamp. These properties are the color, the energy,
25
etc. Due to the fact that the gameEngine 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 recieve realtime lighting in gameBlender the face has to be set to "Light" in the Paint/FaceButtons (See Chapter 4). With the layer settings for lamps and objects (EditButtons, F9) you can control the lighting very precise. Lamps only affect faces on the same layer(s) as the lamp. Per Layer you can use eight lamps (OpenGL limitation) for realtime lighting.
The "Lamp" and "Spot" lights can be sensitive to the distance. Use the "Dist:", "Quad1:" and "Quad2:" settings for this. The mathematics behind this are explained in the Ofcial Blender 2.0 Guide (http://www.blender.nl/show Load a demo le (blends/LampTypes.zip) showing the lamp types in the gameEngine. Press PKEY to launch the demo. Load the MovingLights.blend (blends/MovingLights.blend) demo to see how to animate lamps.
26
position or orientation of an object may not correspond with the velocity. For dynamic objects its better to use the linV and angV for explicitly dening the motion.
As soon we have dened a mass for our dynamic object it will be affected by gravity, causing it to fall until it hits another object with its bounding sphere. The size of the bounding-sphere can be changed with the "Size:" parameter in the RealtimeButtons. The gravity has a value of 9.81 by default: you can change this in the WorldButtons with the "Grav" slider. A gravity of zero is very useful for space games or simulations.
Use the "Damp:" and "RotDamp:" settings to suggest the drag of air or other environments. Dont use it to simulate friction. Friction can be simulated by using the dynamic material settings.
Dynamic objects can bounce for two reasons. Either you have Do Fh enabled and have too little damping, or you are using a Restitut value in the dynamic material properties that is too high.
If you havent dened a material, the default restitution is 1.0, which is the maximum value and will cause two objects without materials to bounce forever.
In the rst case, increasing the damping can decrease the amount of bounce. In the later case dene a material for at least one of the colliding objects, and set its Restitut value to a smaller value. The Restitut value determines the elasticity of the material. A value of zero denotes that the relative velocity between the colliding objects will be fully absorbed. A value of one denotes that the total momentum will be preserved after the collision. Damping is a decrease of velocity in % 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. 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 coefcient, 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 than the object will start sliding. 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 RealTimeButtons (F8) will enable anisotropic friction. After selecting this button, three sliders will appear in which the relative coefcient for each of the local axes can be set. A relative coefcient of zero denotes that along the corresponding axis no friction is experienced. A relative coefcient of one denotes that the full friction applies along the corresponding axis. If you have suggestions or questions concerning the gameBlender physics please contact Gino ([email protected]) (mailto:[email protected]).
27
2.9. Expressions
Expressions can be used in the Expression Controller, the Property Sensor and the Property Actuator. Table 2-1. Valid expressions Expression type Integer numbers Float number Booleans Strings Properties Sensornames Example 15 12.23224 TRUE, FALSE "I am a string!" propname sensorname (as named in the LogicBrick)
Table 2-2. Arithmetic expressions Expression EXPR1 + EXPR2 EXPR1 - EXPR2 EXPR1 * EXPR2 EXPR1 / EXPR2 EXPR1 > EXPR2 EXPR1 >= EXPR2 EXPR1 < EXPR2 Example Addition, 12+3, propname+21 Subtraction, 12-3, propname-21 Multiplication, 12*3, propname*21 Division, 12/3, propname/21 EXPR1 greater EXPR2 EXPR1 greater or equal EXPR2 EXPR1 less EXPR2
Table 2-3. Boolean operations Operation NOT EXPR EXPR1 OR EXPR2 EXPR1 AND EXPR2 EXPR1 == EXPR2 Example Not EXPR logical OR logical AND EXPR1 equals EXPR2
Examples:
28
Table 2-4. Expression examples Expression 12+12 Result 24 Explanation Addition String comparison between a Property and a string A string compare is done
2.10. SoundButtons
The SoundButtons are for loading and managing sounds in gameBlender. Look at Section 2.11 for a possibility to visualize the waveform. Figure 2-9. The SoundButtons
In the SoundButtons header you can see the name of the SoundObject (here "SO:MiniGunFire.wav"). This name is set to the name of the sound sample by default. With the MenuButton you can browse existing SoundObjects and create new SoundObjects. The blue color of the sound name indicates that more than one user uses the sound, the number button indicates the number of users. In the SoundButtons you can then assign or load samples in the SoundObject. So the SoundObject name doesnt have to be the name of the sample. For example you can use a SoundObject "SO:explosion" and then load "explosion_nuke.wav" later. You load samples with the "Load Sample" button in the SoundButtons. The sample name and the location on disk are shown in the text eld to the right of the "Load Sample" button. With the MenuButton left to the location, you can browse already loaded samples and assign it to the SoundObject. The NumberButton indicates how many SoundObjects share the sample. When the pack/unpack button (parcel) is pressed, the sample is packed into the *.blend le, which is especially important when distributing les. The "Play" button obviously plays the sound, the "Loop" button set the looping for the sample on or off. Depending on the play-mode in the Sound Actuator this setting can be overidden. The "Vol:" slider sets the global volume of the sound.
29
Pitch: with the pitch you can change the frequency of the sound. Currently theres 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 next row of buttons lets you dene 3D sound. With the Button "3D vol" activated (which deactivates "Fixed") you enable 3D sound. This means the volume of the sound dependends on the distance between the sound source and the listener. The listener is the active camera. The "Attn:" slider sets the sound attenuation. In a 3D world you want to scale the relation 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. Currently, the scaling factor can be set between 0.0 (all positions get multiplied by 0: no matter where the source is, it will always sound as if it was playing in front of you) and 1.0 (a neutral state, for all positions get multiplied by 1). The next row of buttons denes the stereo position of the sound. With "3D pan" activated the volume for the left and right stereo channel of the sound is dependant of the position relative to the listener. When "Fixed" is activated you can manually pan the sound with the "Pann:" slider. Figure 2-10. 3D sound demo
30
2.11. SoundWindow
Figure 2-11. The SoundWindow
The SoundWindow is used to load and visualize sounds. You can grab and zoom the window and its content like every other window in Blender. The green bar indicates the position of the FrameSlider. This can be used to synchronize a sound with an IPO animation. In the lower part of the window you also have an indicator of the sound length in seconds. In the SoundWindow header see the usual window buttons, the user buttons and some information about the sound.
31
5. Use ALT-D (instanced mesh for new object) when replicating meshes, this is better then SHIFTD (copies the mesh) 6. Alpha mapped polygons are expensive, so use with care 7. Switching off collision ag for polygons is good for performance, also the use of ghost is cheaper then a regular physics object 8. 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. 9. Keep your texture-resolution as low as possible. You can work with hi-res versions and then later reduce them for publishing the game (see Chapter UV Texturing) 10. Polygons set to "Light" are expensive. A hardware acceleration with Transform and Lighting calculation will help here. 11. Instead of real-time lighting use VertexPaint to lighten, darken or tint faces to suggest light situations.
32
3.1. Sensors
Sensors act like real senses; they can detect collisions, feel (Touch), smell (Near), view (Ray, Radar).
The button labeled "X" deletes the Sensor from the gameLogic. This happens without a conrmation, so be careful. The MenuButton right to 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 popup menu. Next is a TextButton, 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.
Name your LogicBricks 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. The next row of buttons is used to determine how and at which frequency a Sensor is "ring". This topic is a bit complex, so we will give examples in more than one part of this documentation.
33
all inputs. When a Controller is triggered, and after evaluation of all inputs, it can either decide to execute the internal script or to send a pulse to the Actuators. An Actuator reacts to a pulse in a different way, with a TRUE pulse it switches itself ON (makes itself active), with a FALSE pulse it turns itself OFF. Figure 3-2. Pulse Mode Buttons
The rst button activates the positive pulse mode. Every time the Sensor res a pulse it is a positive pulse. This can be used, for example to start a movement with an Motion Actuator. The button next to it activates the negative pulse mode, which can be used to stop a movement.
If none of the pulse mode buttons are activated the Always Sensor res exactly one time. This is very usefull for initialising stuff on game start.
The button labeled "f:" (set to 41 here), determines the delay between two pulses red by the Sensor. The value of "f:" is given as frames. The "Inv" button inverts the pulse, so a positive (TRUE) pulse will become negative (FALSE) and vice versa. Get a example le here:pulses.blend (blends/LogicBricks212/1.sensors/pulses.blend).
34
Change the rst dLoc eld (they are ordered x, y, z) to 0.10. Move your mousecursor over the big 3DWindow and press PKEY to start the gameEngine. Now press the key you assigned to the Keyboard Sensor and the plane should move to the right. A more complex example can be found in the LogicBricks examples (blends/LogicBricks212.zip), keyboard.blend (blends/LogicBricks212/1.sensors/keyboard.
By activating the "All keys" Button, the Sensor will react on every key. In the "Hold" elds you can put in modier keys, which need to be held while pressing the main key.
Python methods:
setKey( int key );
35
Python methods:
int xposgetXPosition( );
36
This way you can achieve effects like a lava material causing the player to die when he touches it.
Python methods:
setTouchMaterial( (char* matname) );
Python methods:
setTouchMaterial( (char* matname) );
37
The near sensor only senses objects of the type "Actor" (a dynamic object is also an actor).
If the "Property:" eld is empty, the near sensor reacts on all actors in its range. If lled with a property name, the sensor only reacts on actors carrying a property with that name. The range (spherical) of the near sensor you set with the "Dist" NumberButton. The "Reset" value denes at what distance the near sensor is reset again. This is helpful to avoid multiple pulses when an actor is just at the "Dist" distance, or to open a door at a certain distance but close it on a different distance.
38
Python methods:
setProperty( (char* propname) );
Gets the Property the Near Sensor reacts on More to come... Examples for the use of the Near Sensor are an enemy reaction when the Player gets close, a door opening, etc. For an example le look at the LogicBricks examples (blends/LogicBricks212.zip), near_property.blend (blends/LogicBricks212/1.sensors/near_property.blend).
39
In the "Ang:" eld you can enter an opening angle for the radar. This equals angle of view for a camera. The "Dist:" setting determines how far the Radar Sensor can see. Objects cant block the line of sight for the Radar Sensor. This is different for the Ray Sensor (see Section 3.1.10). You can combine them for making a radar thatss not able to look through walls.
Examples:
Logic Bricks examples (blends/LogicBricks212.zip). radar3.blend (blends/LogicBricks212/1.sensors/radar3.blend).
The property sensor of the type "Equal" checks for equality of the property given in the "Prop:" eld and the value in "Value:". If the condition is true, it res pulses according to the pulse mode settings. The "Not Equal" checks for inequality and then res its pulses.
40
The "Interval" type property sensor res its pulse if the value of property is inside the interval dened by "Min:" and "Max:". This sensor type is especially helpful for checking oat values, which you cant depend on to reach a value exactly. This is most common with the "Timer" Property. The "Changed" Property Sensor gives pulses every time a Property is changed. This can for example happen through a Property Actuator, a Python script or an Expression.
Python methods:
setProperty( (char* propname) );
Sets the type of the Property Sensor. 1. Equal 2. Not Equal 3. Interval 4. Changed
41
Examples:
Logic Bricks examples (blends/LogicBricks212.zip). property.blend (blends/LogicBricks212/1.sensors/property.blend).
With a seed of zero the Random Sensor works like an Always Sensor, which means it res a pulse every time.
Python methods:
setSeed( (int seed) );
Examples:
LogicBricks examples (blends/LogicBricks212.zip). random.blend (blends/LogicBricks212/1.sensors/random.blend ).
42
Without a material or property name lled in, the Ray Sensor reacts on all objects.
Python methods:
list [x,y,z] getHitPosition( );
Returns the normal vector how the ray hits the object.
list [x,y,z] getRayDirection( );
Examples:
Logic Bricks examples (blends/LogicBricks212.zip). ray.blend (blends/LogicBricks212/1.sensors/ray.blend).
Known issues:
Only Y-Axis works for now, as workaround use an Empty to carry the Ray Sensor and rotate it in such a way that the Y-Axis points along the desired direction. If the Ray Sensor refuses to work with a Material as trigger check if the latest object created has the desired material, if not assign it to it (perhaps you need to make a helper object).
43
3.2. Controllers
Controllers act as the brain for your game logic. This reaches from very simple decisions like connecting two inputs, over slightly complex expressions, to complex Python scripts which can carry articial intelligence.
The AND Controller combines one, two or more inputs from Sensors. That means that all inputs must be active to pass the AND Controller.
Examples:
LogicBricks examples (blends/LogicBricks212.zip). and.blend (blends/LogicBricks212/2.controllers/and.blend).
3.2.2. OR Controller
The OR Controller combines one, two or more inputs from Sensors. OR means that either one or more inputs can be active to let the OR Controller pass the pulse through.
Examples:
LogicBricks examples (blends/LogicBricks212.zip). or.blend (blends/LogicBricks212/2.controllers/or.blend).
The expression mechanism prints out errors to the console or in the DOS window, so have a look there if anything fails.
44
Examples:
LogicBricks examples (blends/LogicBricks212.zip). expression.blend (blends/LogicBricks212/2.controllers/expression.blend). More on using Expressions can be found in Section 2.9.
The Python controller is the most powerful controller in gameBlender. You can attach a Python script to it, which allows you to control your gameObjects ranging from simple movement up to complex gameplay and articial intelligence. Enter the name of the script you want to atach to the Python Controller into the "Script:" eld. The script needs to be existant in the scene or Blender will ignore the name you type.
Remember that Blender treads names case sensitive! So a script "player" is not the same as "Player".
Python methods:
Actuator* getActuator( char* name , );
Examples:
45
3.3. Actuators
Actuators are the executing LogicBricks. They can be compared with muscles or glands in a life form.
The Motion Actuator is surely the most important Actuator. It moves, rotates or applies a velocity to objects. The simplest case of using a Motion Actuator is to move the object. This is done with the "dLoc" values in the third row. Every time the actuator is triggered by an impulse it moves the object the amount given in the "dLoc" row. The three values here stand for X-, Y- and Z-axis. So when you enter a 1.0 in the rst eld the object is moved one unit per time unit of the game (the clock in the gameEngine ticks in frames, roughly 1/25 of a second, for exact timings use the Time Property). A simple example is given in the Keyboard Sensor section. The buttons labeled "L" behind each row in the motion actuator, determine if the motion applied should be treated as global or local. If the button is pushed (dark green) the motion is applied based on the local axis of the object. If the button is not pressed the motion is applied based on the global (world) axis. Force Values in this row act as forces that apply to the object. This works only for dynamic objects. Torque Values in this row act as rotational forces (Torque) that apply to the object. This works only for dynamic objects. Positive values rotate counter-clock-wise. dLoc Offset the object as indicated in the value elds
46
dRot Rotate the object for the given angle (36 is a full rotation). Positive values rotate clock-wise. linV Sets the velocity of the object to the given values. angV Sets the angular velocity to the given values. Positive values rotate counter-clock-wise
The Motion Actuator starts to move objects on a pulse (TRUE) and stops it on a FALSE pulse. To get a movement over a certain distance, you need to send a FALSE pulse to the motion actuator always. See the demo le"blends/MoveCertainDist.blend" (blends/MoveCertainDist.blend) for an example.
Python methods:
setForce( list [x,y,z] , bool local );
47
Examples:
LogicBricks examples (blends/LogicBricks212.zip). motion.blend (blends/LogicBricks212/3.actuators/motion.blend). motion_LinV.blend (blends/LogicBricks212/3.actuators/motion_LinV.blend).
With the MenuButton you specify the channel of which freedom should be constrained. With the NumberButtons "Min" and "Max" you dene the minimum and maximum values for the constraint selected. To constrain an object on more than one channel simply use more than one Constraint actuator.
Examples:
LogicBricks examples (blends/LogicBricks212.zip).
Python methods:
setDamp( int damp );
48
);
);
);
setLimit( ? limit );
49
Known issues:
Damping is not working in Blender 2.12 Constraint for rotation not implemented in 2.12
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.
50
Python methods:
SetType( ??? , );
);
);
);
int frameGetStart( );
int frameGetEnd( );
Examples:
LogicBricks examples (blends/LogicBricks212.zip). mouse_button.blend (blends/LogicBricks212/1.sensors/mouse_button.blend). Studio3.blend.gz (blends/Studio.blend.gz) Complete example to move, switch and zoom two cameras in a studio environment. The zoom uses the IPO Actuator together with a Lens-Ipo for the cameras.
51
The Camera Actuator tries to mimic a real cameraman. It keeps the actor in the eld of view and tries to stay at a certain distance from the object. Also the motions is soft and there is some delay in the reaction on the motion of the object. Fill in the object that should be followed by the camera (you can also use the Camera Actuator for non-camera objects) into the "OB:" eld. The eld "Height:" determines the height the camera stays above the object. "Min:" and "Max:" are the bounds of the distance from the object in which the camera is allowed to move. The "X" and "Y" buttons specify behind which axis of the object the camera tries to stay.
Examples:
Logic Bricks examples (blends/LogicBricks212.zip). camera.blend (blends/LogicBricks212/3.actuators/camera.blend).
Known issues:
2.12: Visibility check not implemented, so an obstacle can cover the object. camera.blend (blends/LogicBricks212/3.actuators/camera.blend).
The Sound Actuator plays a SoundObject loaded with the SoundButtons (see Section 2.10).
52
Loop Stop Plays and repeats the sound, when a positive pulse is given. Loop End Plays the sound repeatedly, when a positive pulse is given. When the pulse stops the sound is played to its end.
Examples:
LogicBricks examples (blends/LogicBricks212.zip). sound_property.blend (blends/LogicBricks212/3.actuators/sound_property.blend).
Known issues:
2.12: Sound only on Windows and Linux implemented
Property modes
Assign Assigns a value or Expression (given in the "Value" eld) 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:" eld. Copy
This copies a Property (here "Prop: SProp") from the Object with the name given in "OB: Sphere" into the Property "Prop: Proppy". This is an easy and safe way to pass information between objects.
53
Python methods:
SetProperty( char* name );
Examples:
LogicBricks examples (blends/LogicBricks212.zip). More on using Expressions can be found in Section 2.9.
The Add Object actuator adds an object to the scene. The new object is oriented along the x-axis of the creating object.
Keep the object you like to add on a seperate and hidden layer or it will not work as expected.
Enter the name of the Object to add in the "OB:" eld. The "Time:" eld determines how long (in frames) the object should exist. The value "0" denotes it will exist forever. Be careful not to slow down gameBlender by generating too many objects! If the time an object should exist is not
54
predictable, you can also use other events (collisions, properties, etc.) to trigger an "End Object" for the added object by using LogicBricks. 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 added object.
Python methods:
setObject( char* name );
Time in frames the added Object should exist. Zero means unlimited
int time getTime( );
End Object
The "End Object" type simply ends the life of the object with the actuator when it gets a pulse. This is very usefull for ending a bullets life after a collision or something similar.
55
Replace Mesh
The "Replace Mesh" type, replaces the mesh of the object by a new one, given in the "ME:" eld. Remember that the mesh name is not implicitly equal to the objectname.
Python methods:
setMesh( char* name );
Track to
The "Track to" type, rotates the object in a way that the y-axis points to the target specied in the "OB:" eld. Normally this happens only in the x/y plane of the object (indicated by the "3D" button not pressed). With "3D" pressed the tracking is done in 3D. The "Time:" parameter sets how fast the tracking is done. Zero means immedeately, values above zero give a delay (slower) in tracking.
Python methods:
setObject( char* name );
56
setUse3D( );
bool 3d setUse3D( );
Examples:
LogicBricks examples (blends/LogicBricks212.zip). end_object2.blend (blends/LogicBricks212/3.actuators/end_object2.blend). add_object2.blend (blends/LogicBricks212/3.actuators/add_object2.blend). Studio3.blend.gz (blends/Studio.blend.gz) Example of a studio environment, uses Replace Mesh to switch a TV screen.
Simply restarts and resets the scene. It has the same effect like stopping the game with ESC and restart with PKEY.
57
Set Scene
Switch to the scene indicated into the text eld. During the switch all properties are reset!
Python methods:
setScene( char* scene );
Set Camera
Python methods:
setCamera( char* camera );
Examples:
SetScene.blend (blends/SetScene.blend).
58
SetCamera.blend (blends/SetCamera.blend). Studio3.blend.gz (blends/Studio.blend.gz) Complete example to move, switch and zoom two cameras in a studio environment.
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 classical random 50-50 pick. It results in TRUE or FALSE with the same chance. This is like a (ideal) coin-pick. Boolean Bernoulli
This random function results also 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
59
"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:" eld 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 innite number of picks. Float Constant
For debugging your game logic with a given value. Float Uniform
This returns a random oating point value between "Min:" and "Max:".
60
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.
Python methods:
setSeed( int seed );
Sets the random seed (the init value of the random generation)
int seed getSeed( );
Gets the random seed (the init value of the random generation) from the Actuator
float para1 getPara1( );
61
??
int dist getDistribution( );
62
Chapter 4. UV Texturing
Textures have a big impact on the look and feel of your game or interactive environment. With textures you are able to create a very detailed look even with a low poly model. With alpha channel textures you are also able to create things like windows or fences without actually modeling them.
63
Chapter 4. UV Texturing
disk and makes it possible to change them and share between scenes. But if you want to distribute a le it is possible to pack these resources into the Blendle, so you only need to distribute one le, preventing missing resources. Figure 4-1. The ToolsMenu
The functions for packing and unpacking are summarized in the ToolsMenu. You can see if a le is packed if there is a little "parcel" icon right to the ToolsMenu. After you packed a le, all new added resources are automatically packed (AutoPack).
64
Chapter 4. UV Texturing
65
Chapter 4. UV Texturing
The rst Icon keeps UV polygons square while editing: this is a big help while texturing. Just drag one or two vertices around and the others are following to keep the polygon square. The second one keeps the vertices inside the area of the image.
With the UserBrowse (MenuButton) you can browse, assign and delete loaded images on the selected faces. "Load" loads a new image and assigns it to the selected faces. "Replace" replaces (scene global) an image on all faces assigned to the old image. The small buttons right to the "Load" and "Replace" buttons opens a FileWindow without the thumbnail images.
66
Chapter 4. UV Texturing
The grid icon enables the use of more (rectangular) images in one map. This is used for texturing from textures containing more than one image in a grid and for animated textures. The following two number buttons dene how many parts the texture has in x and y direction. Use SHIFT-LMB to select the desired part of the image in GridMode. The "Anim" button enables a simple texture animation. This works in conjunction with the grid settings, in a way that the parts of the texture are displayed in a row in game mode. With the number buttons right of the "Anim" button you dene the start and end part to be played. "Cycle" switches between one-time and cyclic play. With the lock icon activated, any changes on the UV polygons in the ImageWindow are shown in realtime in the 3DWindows (in textured mode).
Vertices in the ImageWindow are selected and edited (rotate, grab) like vertices in EditMode in the 3DWindows. Drag the view with the middle mouse, zoom with PAD+ and PAD-.
The following modes always work on faces and display the setting of the active face. Two colored lines in the 3D and the ImageWindow indicate the active face. The green line indicates the U coordinate, the red line the V coordinate. To copy the mode from the active to the selected faces use the copy buttons ("Copy DrawMode", "Copy UV+tex" and "Copy VertCol") in the Paint/FaceButtons. In FaceSelect mode the special menu has some points to quickly set and clear modes on all selected faces, see Figure 4-5.
67
Chapter 4. UV Texturing
Face modes
Tex This enables the use of textures. To use objects without textures disable "Tex" and paint the faces with VertexPaint. Tiles This indicates and sets the use of the tile mode for the texture, see Section 4.3.1. Light Enables realtime lighting on faces. Lamps only affect faces of objects in the same layer as the lamp. Lamps can also be on more than one layer, which makes it possible to create complex real-time lighting situations. See also Section 2.7. 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 gameEngine. If that is not needed, switch off this option to save on resources. Shared With this option vertex colors are blended across faces if they share vertices (currently not implemented in Blender 2.12). Twoside Faces with this attribute are rendered twosided in the gameEngine ObColor Faces can have an animatable color using the ColR, ColG and ColB IPOs. This option replaces the vertexcolors
68
Chapter 4. UV Texturing
Halo Faces with this attribute are rendered with the X-axis always pointing to the active view or camera. Billboard Faces with this attribute are pointing in the direction of the active view with the X-axis. The difference with "Halo" is the faces are only rotated around the Z-axis Shadow (currently not implemented in Blender 2.12). Text Faces with this attribute are used for displaying bitmap-text in the gameEngine, see Section 4.3.3. 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 Depending on the alpha channel, the face is rendered transparent.
Since Blender version 2.04 weve got the ability to draw text in the gameEngine using bitmap fonts. These bitmap fonts can be created from a TrueType or Postscript outline font. For an explanation how to create a bitmap font look for the Tutorial How to create your own bitmap fonts (http://www.blender.nl/showitem.php?id on the Blender site. To get bitmap text or numbers displayed on a single face you need a special bitmap with the font rendered onto it. Then create a property named "Text" for your object and map the rst character of the text-bitmap on it. Check the "Text" face attribute for the face, which should display the text in the Paint/FaceButtons. The type of the property can be every type, so also a boolean will be rendered as "True" or "False". For a complete tutorial look at: Using bitmap fonts in blender 2.04 (http://www.blender.nl/showitem.php?id=42)
69
Chapter 4. UV Texturing
70
Chapter 5. Python
Work in progress! Especially I will add here more Python script examples in future.
Python (www.python.org) 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 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.
The TextWindow can be displayed with SHIFT-F11 or by adjusting the IconMenu in the Windowheader. As usual there is an IconBut to make the TextWindow fullscreen, the next MenuButton can be
71
Chapter 5. Python
used to switch between text les, open new ones or add new text buffers. The x-shaped Button deletes a textbuffer after a conrmation. With the right MenuButton you can change the font for displaying the text. With LeftMouse-Hold and dragging the mouse you can mark ranges of text for the usual cut, copy & paste functions. The keycommands are:
72
Chapter 5. Python
Beside that you can inuence the gameObject that carries the Python Controller directly. This means moving it, applying forces or geting information from this object.
Beside the Python in the gameEngine, Blender also includes Python for modeling and animation tasks.
Now enter the following script (./blends/Python_getPosition.blend) into the TextWindow you just created (you dont need to type the lines starting with "#", these are comments). Figure 5-3. First Script
1 2 3 4 5 6 7 8 9 10
# first gamePython script # gets the position of the owning object # and prints it on the console import GameLogic controller = GameLogic.getCurrentController() owner = controller.getOwner() print owner.getPosition()
The "print" command and errors from the Python interpreter will appear on the console where you started Blender from, or in the DOS window, when running Blender under 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 gameBlender with the PKEY to see the results changing. Now to explain the function of the script line by line. Line ve is maybe the most important line here. We import the GameLogic module which is the basis for all gamePython in Blender.
73
Chapter 5. Python
In line seven we get the Controller, which executes the script and assigns it to the variable "controller". In line eight we use the controller we got in line seven to get the owner, the GameObject carrying the LogicBrick. You can see we use the method "getOwner()" to get the owner of our controller. We now have the owner 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 more possibilities to get that information. Add the following line to the end of the script from Figure 5-3:
1 print dir(owner)
Start the gameEngine again, stop it and look at the console window. You see the following output: [0.0, 0.0, 0.0] [applyImpulse, disableRigidBody,enableRigidBody, getLinearVelocity, getMass, getOrientation, getPosition, getReactionForce,getVelocity, restoreDynamics, setOrientation, setPosition, setVisible, suspendDynamics]
The rst line shows the position of the object, the next lines show the methods, which the "owner" is providing. 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.
74
Chapter 5. Python
You can use the setPosition() or applyImpulse() functions for moving an object from a python script. Another (and a bit easier to understand) way is to change the elds of an Motion Actuator. The script from Figure 5-5 shows the use of this method to move an object in a random way, this is similar to the (brownian) movement of molecules or bacterias. Figure 5-5. Move script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
# Use of python to set actuators and move an object # 29/03/2001 [email protected] # CTRL-LEFTARROW for fullscreen
# Get the controller (which carries the script) contr = GameLogic.getCurrentController() # and the actuator (by name!) move=contr.getActuator("move") # Get a random float (0.0 ... 1.0), this random generates # different sequences every gameEngine start! random = GameLogic.getRandomFloat() # Set the dRot and dLoc in the attached activator (note the last # "1", for local movement! move.setDRot(0,(random-0.5)/5,0,1) move.setDLoc(random/5,0,0,1) # Activate the Actuator
75
Chapter 5. Python
27 GameLogic.addActiveActuator(move,1)
Note the use of the getRandomFloat() function to get the random numbers without unsing a Random Actuator. These random numbers are different on every gameEngine start. The last lines actually set the values in the Actuator and activate it with addActiveActuator(). Figure 5-6. LogicBricks for the brownian movement
Figure 5-6 shows the used logic bricks. Be sure to name the actuator correct because the script is refering to this name to get the actuator! The Add Object Actuator is adding the trail to the moving object. Get a example le here:brown.blend (blends/brown.blend).
# # # #
experimental visibility flag it will hide all objects so objects must be set visible using this script
Rasterizer.enableVisibility(1)
76
Chapter 5. Python
16 17 18 19 20 21 22 23 24 25 26 27
# now set all objects in the range of the near # visible. Try to change "Dist" and "Reset" objects = sensor.getHitObjectList() if objects: for obj in objects: obj.setVisible(1)
For a simple visibility check you assign a Near Sensor to your player as shown in Figure 5-8. The Near Sensor will provide the visibility script with an object list that is inside the Near Sensor range dened by "Dist" and "Reset". Make sure you check the positive pulse mode and set "f:0". Figure 5-8. LogicBricks for the visibility script
# Mouse cursor control import GameLogic import Rasterizer # Get the dimensions of the game window ww = Rasterizer.getWindowWidth() wh = Rasterizer.getWindowHeight() # calculate the aspect (in full screen the aspect of the CRT)
77
Chapter 5. Python
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
aspect = float(wh)/ww # With this value you can calibrate the mouse to the 3D Window actionx=28.0 actiony=actionx*aspect #Get controller, sensor and owner c = GameLogic.getCurrentController() sensor = c.getSensor("mouse") owner = c.getOwner() # I use properties for debugging purpose (use wireframe to see) owner.x = float(sensor.getXPosition()-ww/2)/ww*actionx owner.y = float(sensor.getYPosition()-wh/2)/wh*actiony # Set the position of the crosshair directly # (see SCA, there is no Actuator) owner.setPosition([owner.x,0,-owner.y])
The script is triggered by a Mouse Sensor, set to "Trigger on movement". Note the use of the two Properties, x and y, they are used for debugging but needed for the script to work. If you dont need the Properties replace the occurence of "owner.x" with "x" and "owner.y" with "y". Figure 5-10. Logic bricks for the mouse script
78
Chapter 5. Python
bool active );
This method makes the Actuator "actuator" active ("active=TRUE") or inactive ("active=FALSE").
float getRandomFloat( );
This function returns a random oat in the range of 0.0...1.0. The seed is taken from the system time, so you get a different sequence of random numbers at every game start.
setGravity( [gravityX,gravityY,gravityZ] );
This function returns the width of the Blenderwindow the game is running in.
int getWindowHeight( );
This function returns the height of the Blenderwindow the game is running in.
void makeScreenshot( char* filename );
This sets all objects to invisible when "usevisibility" is TRUE. The game can then set the visibility back to on for only the needed objects.
showMouse( bool show );
Shows the mouse cursor when "show" is TRUE while the gameEngine runs.
setBackgroundColor( [float R,float G,float B] );
79
Chapter 5. Python
This returns the owner, the gameObject has the LogicBrick assigned.
setExecutePriority( int pri );
?
int pri getExecutePriority( );
80
Chapter 5. Python
Returns TRUE if positive pulse mode is active, FALSE if positive pulse mode is not active.
setUsePosPulseMode( bool flag );
Set ag to TRUE to switch on positive pulse mode, FALSE to switch off positive pulse mode.
int getPosFrequency( );
Set the frequency of the updates in positive pulse mode. If the frequency is negative, it is set to 0.
bool getUseNegPulseMode( );
Returns TRUE if negative pulse mode is active, FALSE if negative pulse mode is not active.
setUseNegPulseMode( bool flag );
Set ag to TRUE to switch on negative pulse mode, FALSE to switch off negative pulse mode.
int getNegFrequency( );
Set the frequency of the updates in negative pulse mode. If the frequency is negative, it is set to 0.
bool getInvert( );
Set to TRUE to invert the responses of this sensor, set to FALSE to keep the normal response.
81
Chapter 5. Python
);
Sets the position of the gameObject according to the list of the X, Y and Z coordinate.
pylist [x,y,z] getPosition( );
82
Chapter 5. Python
Returns a list of the X, Y and Z component of the speed. The speed is in Blenderunits/second.
pylist [x,y,z] getVelocity( );
float massgetMass( );
83
Chapter 5. Python
84
Index
Actuator
Camera, 52 Constraint, 48 Edit Object, 54 IPO, 50 Motion, 46 Property, 53 Random, 59 Scene, 57 Sound, 52
Actuators, 46 Add Object, 54 Always, 33 Anim, 67 animated textures, 67 AutoPack, 64 Bugs
Standard Methods, 82
gravity, 27 grid icon, 67 ImageWindow, 65 Ketsji, 17 Keyboard, 34 Lamps, 25 Lights, 25 lock icon, 67 LogicBricks, 33
Standard Methods, 80
Material, 25 Materials, 24 Mouse Sensor, 36 Near Sensor, 38 OpenGL, 26 Pack Data, 63 Paint/FaceButtons, 67 Performance, 31 Physics, 26 Properties, 22 property
Collision Sensor, 37
Property Sensor, 40 Pulse, 33
mode, 34
Python, 71, 72
AND Controller, 44 Expressions, 28 OR Controller, 44 Phyton Controller, 45 Property Sensor, 42 Random Sensor, 42 Scene Actuator, 58
Expressions, 28 Face modes, 68 le formats, 63 gameBlender, 10 GameKeys Module, 80
Property Actuator, 54
Python Controller, 45 Python examples, 74 Python methods
AddObject Actuator, 55 Collision Sensor, 37 Constraint Actuator, 48 IPO Actuator, 51 Motion Actuator, 47 Mouse Sensor, 36
85
Near Sensor, 39 Property Sensor, 41 Python Controller, 45 Random Actuator, 61 Random Sensor, 42 Ray Sensor, 43 ReplaceMesh Actuator, 56 Sensor, 35 SetCamera Actuator, 58 SetScene Actuator, 58 Touch Sensor, 37 TrackTo Actuator, 56
Python modules, 78 Radar Sensor, 40 Random Sensor, 42
Standard Methods, 80
SoundButtons, 29 SoundWindow, 31 Special menu
FaceSelectMode, 67
Specularity, 25 Touch Sensor, 36 UV Editor, 65 UV Texturing, 63 WorldButtons, 27