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

Appendix

The Bottom Line

Each of The Bottom Line sections in the chapters suggest exercises to deepen skills and understanding. Sometimes there is only one possible solution, but often you are encouraged to use your skills and creativity to create something that builds on what you know and lets you explore one of many possible solutions.

Chapter 1: Working in Blender

Understand the difference between datablocks and objects. Mesh datablocks and Mesh objects present a clear example of the distinction between 3D objects and their associated datablocks.
Master It One way to associate two different 3D objects with the same Mesh datablock is to create independent 3D objects and then select the same Mesh datablock from the Mesh drop-down menu. If you do this, you will wind up with an extra unused Mesh datablock that will disappear when Blender is saved and reopened. Find another way to accomplish the same thing, but without leaving any unused Mesh datablocks lying around and without needing to reopen Blender to clear it away.
Solution Create a single Mesh 3D object and link-duplicate it using Alt+D.
Set the options available to you in the User Preferences window. A wide variety of often-overlooked options are available in the User Preferences window, including settings for views, controls, edit methods, and themes, among others.
Master It Create your own preferred default starting state and save it so that it will be active every time you start Blender.
Solution When you’ve set the desired options and have the desired starting window configuration in place, press Ctrl+U to save the settings to a .Blend.blend file. Place this file in your .blender directory and open Blender with your new options in place. (A sample .Blend.blend file is included on the disk that accompanies this book.)
Use lesser-known methods for selecting, grouping, and organizing 3D elements to speed up your workflow. There are numerous ways to select and group objects and 3D elements that can considerably increase your speed and efficiency when working.
Master It Use the selection methods described in this chapter to make the face selections shown in the following graphic.
bapp01uf001.tif
You should be able to make this selection using a single (modified) mouse click followed by a single hot key combination. There are several ways to do this.
Solution Press Alt+RMB on one of the perpendicular edges in the top face loop. Press Shift+G and select Perimeter.

Chapter 2: Working with Textures and Materials

Use Blender’s texturing functionality effectively. Blender has a powerful set of UV-mapping tools that rank among the best in the industry. Using these tools enables you to place 2D textures exactly as you want them on the surface of a 3D model.
Master It Find the file engine.blend among the downloadable support files for this book. Create seams, unwrap the mesh, and export a UV face-layout file for use in GIMP. Apply a UV test grid image to the mesh.
Solution An unwrapping can be found in the file engine_unwrap.blend among the downloadable support files for this book.
Mix textures to create almost any surface effect. By using Blender’s UV texture and texture-baking features, particularly in combination with a powerful image-manipulation application such as GIMP, you can create a wide variety of seamless texture effects.
Master It Using the metal_texture.jpg file included among the downloadable support files for this book, or other textures that you find online or create yourself, use the methods described in this chapter to create seamless color and bump map textures for the engine.blend model.
Solution One solution can be found in the file engine_tex.blend among the downloadable support files for the book.
Make the most of the Blender material system to create complex materials and shaders. Creating textures is only the first part of making convincing materials. Mapping them correctly to the material and setting their parameters correctly are crucial to getting realistic material effects.
Master It Combine the two textures you created in the previous exercise into a single material with both color and bump qualities. Set the shader properties in a way that creates a convincing metallic look.
Solution One solution can be found in the file engine_mat.blend among the downloadable support files for the book.

Chapter 3: Sculpting and Retopo Workflow

Get the most out of Blender’s sculpting functionality. Blender’s multires modeling and sculpting features provide a powerful and versatile set of tools for 3D sculpting. When you finish each of the exercises that follow, try showing your work on a thread in in the Focused Critique forum to get suggestions on how you can improve it.
Master It Nothing is more important than practice for improving your skills at sculpting. Following the guidelines in this chapter, create at least three more sculptures of human heads. Try sculpting old people, women, and men. Try working from orthogonal references as described in this chapter and also try freehand from informal photographs. When you’re comfortable with heads, experiment with working on full-body sculptures. Note your impressions on the differences between the various subject matters and how they are sculpted.
Solution Your model will be unique. Study the file baby.blend and compare how the shapes of the face are modeled to get an idea of how your model is progressing.
Use retopo to convert a sculpted form into a polygon model with correct edge loop geometry. Blender’s retopo feature enables you to create a new model whose shape is identical to another object, making it possible to recast a very high–polygon sculpted object into a lower-polygon model with elegant edge loop geometry that can be easily deformed, animated, and rendered.
Master It Select the model you are most happy with from the previous exercise and use retopo to create a lower-poly model of the same shape. Pay attention to edge loop geometry, and keep the density of the mesh as low as you can while representing the underlying shape as accurately as possible.
Solution Your model will be unique. Study the structure of the retopo model in the baby_retopo.blend file to get a sense of how your model is progressing.
Use normal map baking to capture finely sculpted detail for use on a low-poly model. In order to represent the detail of a very high–poly sculpted object, Blender enables you to bake the surface normal information of the sculpted object onto a 2D texture called a normal map, which is then used as a UV texture on the lower-poly model, yielding the illusion of a highly detailed surface.
Master It Follow the steps described in this chapter to bake a normal map from your sculpted object to the retopologized model you created in the previous exercise.
Solution A successful normal map should make your rendered retopo mesh look as similar as possible to the original sculpted mesh. The image of the three baby heads in this chapter will give you a rough idea of the kind of similarity you should see.

Chapter 4: Rendering and Render Engines

Understand rendering options and render passes. You can obtain a variety of 2D effects using plane-mapped textures, shadeless materials, toon shaders, and the edge feature in Blender’s Internal renderer.
Master It Use the Toon Shader option and the Edge Render option (you’ll find them under Post-Processing in the Render properties area) to re-create the scene from scene.blend as a toon-styled image. If you’re especially interested in toon or non-photo-real rendering, or you just want a challenge, go to and download an experimental build of Blender with the Freestyle line renderer integrated. Google for some tutorials to get started, and see what you can come up with using that renderer.
Solution You can find a toon-style scene in the downloadable file toon.blend.
Work with the Cycles rendering engine. Cycles has a variety of shader settings, which can be combined in a nearly unlimited number of ways, yielding a wide variety of material effects.
Master It Using texture nodes and differently colored glass shaders, create a convincing glass marble. Use either the HDR image from the book files for lighting, or find another panoramic HDR image online and use that. More information on the science of HDR can be found at .
Solution The file marble.blend contains a sample solution.
Take advantage of distributed community-based rendering on Renderfarm.fi for heavy jobs. Renderfarm.fi is a distributed rendering resource for animations, which can divide your rendering tasks among many volunteers throughout the world, making for much quicker total render times.
Master It Render 100 frames’ worth of the scene in scene.blend on the render farm. Try it using both the Cycles version and the Blender Internal version, and render it in at least three different sizes. Figure out which sizes and which sample values are too low to see an improvement in render times.
Solution The results will vary depending on the time you spend on the queue for each job and the sizes and sample values you use. With a few experiments, you will start to get a sense of what kind of improvements you can expect. Of course, even if the overall render time is slower on Renderfarm.fi, it may still be worth using in order to free up your own computer to work on.

Chapter 5: Getting Flexible with Soft Bodies and Cloth

Control the behavior of soft body objects. Soft body meshes suffer from a disadvantage in that they lack internal structure. Although bending parameters can counter this somewhat, there are some cases in which the fully 3D structure of a matrix can come in handy for giving a soft-body simulation more of a sense of volume.
Master It Try to construct a cube of gelatin from a mesh cube by using a soft-body-modified lattice for the deformation. Figure out how best to weight-paint the cube so that the lattice deformation is convincing.
Solution Check the file lattice.blend for a sample solution to this exercise.
Work with force fields, collision objects, and modifiers. You can obtain realistic cloth movement effects by combining rigging, pinning, and hook modifiers with the free movement of the cloth simulation.
Master It Using a cloth setup similar to the curtains shown in this chapter, create a curtain that can be animated to open in a realistic way, as though it were hung with hooks on a curtain rod.
Solution A straightforward way to do this is to pin vertices to empty hooks and to bone-parent the hooks to a single bone in the position of the curtain rod. The opening motion can then be controlled by scaling down the bone. You can see an example in the file curtain.blend, available on the website for this book.
Work with cloth and clothing. There are a variety of approaches to take with creating clothing, ranging from modeling the cloth forms directly, to using the cloth simulator as a median step in modeling, to animating with the cloth simulation directly. All of these approaches have their appropriate uses.
Master It Try to create different articles of clothing for your characters. Experiment with boots, scarves, trousers, shirts, and dresses. Which approaches do you think work best for which types of clothing? What do you think the best way to animate a long, stiff jacket might be?
Solution You’ll find that in general, the tighter the fit of the clothing, the less appropriate a cloth simulation will be, and the looser the fit (for example, a cape or a free-flowing dress), the more you should rely on cloth simulation for the actual motion of the cloth. For a long, stiff jacket, you might try rigging the tail or hem of the jacket with bones and using hooks to control the bones. The hooks can then be vertex parented to vertices in a simple dummy cloth or Soft Body object.

Chapter 6: Working with Particles

Work with emitter particles. This chapter discussed the options available to you for working with particles in Blender 2.6. Particles enable the simulation of very small objects such as dust, snowflakes, or insects and are the basis for smoke simulations and fluid splashes. They are also used by the Explode modifier to control bits of a broken object that has been exploded.
Master It You saw how to use the Explode modifier in this chapter and also how to use collision objects to deflect particles. Using both of these tools, set up a simulation of a ball striking a wall and shattering on contact. Animate the motion of the ball against the wall by hand and then control the shattering using particle property settings. Make sure the pieces of the ball collide with the wall and floor convincingly.
Solution A sample solution can be seen in the file smash.blend among the downloadable files for this chapter.
Work with boids. Boids are a method of simulating the behavior of large groups of small living creatures (at least, small compared to the size of the group), such as swarms of insects, schools of fish, or flocks of birds.
Master It The options to allow land movement and to allow flight can be animated. Deflection objects can be used to give walking boid groups a surface over which to walk. Set up a boid system that begins by swarming like ants over a bumpy ground surface and then takes flight in the middle of the animation.
Solution An example of such a boids setup can be found in the file bugs.blend in the downloadable files for this chapter.
Create hair effects with particles. Hair particles enable you to have a great deal of control over the appearance and behavior of your characters’ hairstyles.
Master It You’ve seen a detailed example of how to comb a long-haired character and to use weighted vertex groups to influence hair density. Similar tools can be used to create short hairstyles. On a character mesh or an ordinary sphere, create a hairstyle that resembles a military-style flat-top fade haircut. Make sure that the fade is as tidy as you can possibly make it.
Solution Of course, there are several ways to do this, but the fade is probably best accomplished by using a weighted vertex group to control the length of the hair. In the file flattop_fade.blend you can see an example of this. Combing the hair upward and cutting it flat using the Cut tool will get you the flattop.

Chapter 7: Volumetric Fluid, Smoke, and Fire

Use the Blender fluid simulator. This chapter discussed Domain, Fluid, Inflow, Outflow, Particle, and Obstacle objects. In the Fluid drop-down, there is one more object type, called Control. This object enables you to use mesh objects to attract or repel fluid for special effects.
Master It Experiment with the Control object type, using an animated Attraction Force Strength value. Create a fluid simulation in which fluid rises from a bath to create a spherical shape hovering above the surface of the bath and then splashes back down from the sphere into the surface it originally came from.
Solution A sample solution can be found in the .blend file control.blend in the downloadable files for this book.
Get the shot. When fluid interacts with obstacles, the fluid resolution becomes especially important. As you saw in the bottle example, obstacles must always be bigger than the size of fluid voxels. Other issues can arise when fluids conform to the shapes of their containers, requiring high-resolution simulations to address the problem.
Master It Set up a fluid simulation to flow from an Inflow to an Outflow object, in the process moving through a clear, curved glass pipe. Make sure that the pipe is fully modeled, with inside and outside surfaces, and that it has enough real geometry to make the fluid conform to its actual shape. (Fluid modifiers cannot be placed below Subsurf modifiers in the stack, so fluid can only interact with the real geometry of obstacles.) What issues arise? Where do you see problems that require higher fluid resolution to solve them?
Solution When fluid conforms to curved containers, the fixed curved surface of the fluid in contact with the container can become “voxelated” and show aliasing patterns. An example can be seen in the pipe.blend file included with the downloads for this book. If the container is not clear, these will normally not be visible, but in the case of a clear container, these patterns will be noticeable and unsightly. The only solution, aside from concealing these surfaces, is to run the simulation at a high enough resolution to make the voxels too small to be noticeable. Volume resolution is very demanding on resources, so it may require some serious computer firepower to completely eliminate this effect.
Simulate smoke and fire. You can have a great deal of control over the behavior of a smoke simulation by manually adjusting the settings of the particle system the simulation is based on.
Master It Using what you’ve learned in this chapter combined with what you learned about particles in Chapter 6, set up a convincing explosion with smoke and flame. For an extra challenge, use a second object with a second particle system to create a double blast, with the two explosions offset in time by a few frames.
Solution A sample solution can be found in the .blend file explode.blend in the downloadable files for this book.

Chapter 8: Bullet Physics and the Blender Game Engine

Use the appropriate collision bounds for what you need. Bullet enables a variety of different collision bound types, which vary in how quickly they can be calculated for real-time interaction and in how accurate and realistic the collisions are that they can produce.
Master It Create a rigid body simulation consisting of a ball, a plane, and a torus. Make the torus and the ball drop onto the plane such that they both exhibit realistic rigid body behavior and the ball drops into the hole in the torus.
Solution The ball will be a Sphere Collision object, with the radius value set appropriately. The torus will be a Triangle Mesh object. You can see an example in balltorus.blend file available in the downloadable files for this book.
Experiment with cutting-edge physics features. When doing paid work or other mission-critical projects, it’s safest to work with a single official release of Blender from the beginning of the project to the end. However, a lot of times you may find yourself wanting or needing to work with developmental features. This is fine, but it requires some caution. Try to stay abreast of development notes and always keep your work safely backed up. Keeping some backup files “quarantined” by not opening them with development builds will ensure that you never lose an unacceptable amount of work because of development bugs.
That said, for the purposes of learning, there’s no reason not to work with the most bleeding-edge builds available. Learning new things incrementally is much easier than having to relearn Blender from scratch every few years. If you haven’t done so already, you should download a copy of the Bullet integration branch from Graphicall.org and familiarize yourself with its features.
Master It Set up a rigid body simulation with animated parts, along the lines of the one in the second section of this chapter, using the most recent Bullet integration development build for your system from Graphicall.org. Run the simulation without using the game engine.
Solution By the time you read this, the developmental builds will have advanced considerably, so I can only speculate on the details of the implementation. You’ll find the rigid body settings in the Physics properties area. At the time of this writing, there is an Animated check box on the Rigid Body physics panel that can be checked to indicate which objects respond to keyframed animation curves.
Take ragdoll physics to the next level with Bullet integration. Bullet integration will be a welcome development for a variety of reasons. One thing that it enables is integration of ragdoll physics with keyframed character animation, making ragdoll simulation much more interesting.
Master It Using a simple ragdoll setup such as the one described in this chapter, create an animation in which a character is struck by a heavy flying object while walking along and then picks himself up off the floor.
Solution The basics of character keyframe animation are covered in Introducing Character Animation with Blender, 2nd Ed. (Sybex, 2011). You will need to keyframe the influence of the rigid body simulation on the components of the ragdoll. You will also need to keyframe the influence of the other modifiers and constraints. Try to find the simplest setup that yields good results.

Chapter 9: Compositing with Nodes

Use the Blender composite node system to pull a green screen matte. When you know in advance that you will be compositing a character or object into a scene, a common technique is to shoot the original video of the foreground figure against a colored background screen. This makes it possible to eliminate the background quickly and easily by using color channels in the node compositor.
Master It Using a nodes setup based on the example in this chapter, add a background image from an image file to create a fully composited image such as the one shown in Figure 9-64. You can use the sky_map.jpg file included on the CD.
Solution See the file greenscreen_final.blend for a possible solution to this exercise.
Use the AnimAll add-on for garbage matting. Background clutter in the original footage can cause imperfections in the matte. To block these out, garbage matting is used. In cases when the garbage matte must interact with the silhouette of the foreground figure, some hand keying or rotoscoping may be necessary.
Master It Using a 3D curve animated with the AnimAll add-on, add a second garbage matte to the video example used in this chapter to cover the debris in the background of the right side of the frame.
Solution See the file greenscreen_final.blend for a possible solution to this exercise.
Manipulate the video’s color channels to reduce color spill. Any time you composite footage shot under one set of lighting conditions with footage shot under another set of lighting conditions, color mismatches can occur. This is particularly the case when a green screen is used, which can cause a green cast or spill in the original footage. To eliminate this, it is possible to work directly with the color channels to adjust the mix of red, green, and blue energy in the image to better match the background.
Master It In the composited image you made in the first “Master It” exercise of this chapter, create a slightly purple screen that affects only the most brightly lit highlights of the foreground figure to attain results similar to those in Figure 9-65.
Solution See the file greenscreen_final.blend for a possible solution to this exercise.

Chapter 10: Advanced 3D/Video Compositing

Track camera movement in the Movie Clip Editor. Blender’s new camera-tracking functionality enables you to capture camera movement data directly from live-action video clips by placing tracking markers at key points in the 2D video and setting Blender loose to calculate the dimensions of the space and the rotation and location of the camera throughout the clip.
Master It Track the camera in a video of your own. For easiest tracking, try to use a video with lots of lateral camera movement and many high-contrast, motionless visible points to use as tracking markers. Also, be sure you have as much data about your camera and the field of view used for the video as possible. Use the documentation of your camera or Google to find out the sensor size and make a note of the zoom position you used. Try to get your track down to an error value of less than one pixel for sure and less than half a pixel if possible.
Solution The details of the solution will depend on your video footage. Check the file track.blend for a solution for the provided video footage. As modern directing tastes have shown, camera tracking has changed how we approach filming. Instead of having shaky-cam video footage from the start, it’s become the norm to film with smoothness and precision, pull a track with little hassle, and add camera shake as a post-process.
Composite 3D content into camera-tracked video. With a combination of camera tracking and masking you can create sophisticated composites of 3D content and live video.
Master It In the example in this chapter, you saw how a cube could be placed into a live-action video scene. I placed the cube on the left side of the sidewalk closest to the storefronts to avoid it being walked past by the man talking on the phone. Track and reconstruct the scene yourself, but this time place the cube on the left side of the sidewalk, next to the subway entrance. Use masking to enable the man walking by to obscure the cube as he passes.
Solution Take a look at the mask.blend file to see a finished result for this exercise.
Use masking in the Clip Editor. Blender’s new Clip Editor masking functionality has vastly improved on the previous approach of using a Curve object in the 3D space. Using masking, you can control exactly which portions of an image are used in a composite. You can even control the degree of feathering of a mask on a control-point level.
Master It Using the video clip provided for Chapter 9, redo the garbage-matting tutorial using the masking functionality of the Clip Editor.
Solution The results should be the same as they were using the Chapter 9 method. If you run into trouble, review the section of this chapter on using the masking tool.

Chapter 11: Working with the Video Sequence Editor

Import, edit, and render video with the Blender VSE. Blender’s Video Sequence Editor (VSE) is a powerful tool for cross-platform, multiformat video editing. One of its key strengths is the ease with which it can handle a variety of different image, video, and audio formats both as input and as rendered output.
Master It Download the video idol_clip.mov from the website for this book. Using a Transition strip, animate the video image rotating in place. Render the resulting movie to a series of JPEG images.
Solution Select the video strip and add a Transition strip. Set your end frame at 240 in the timeline. In the Effect Strip panel, keyframe Rotation at 0 on frame 1. Advance to frame 241 and set the Rotation to 360. In the F-Curve Editor, select the Rotation F-Curve and set its extrapolation mode to Linear Extrapolation. Select Jpeg from the drop-down menu in the Format panel in the Render properties area, make sure Sequencer is checked in Post Processing, and then click Render Animation.
Create transitions, overlays, and effects for your videos. The VSE has a variety of built-in effects and transitions to enable you to edit video and do simple compositing quickly and easily. Alpha values of 3D scenes also work seamlessly within the VSE.
Master It Add a caption for the robot’s line “Checkmate” in the video end_zone_clip.avi. Render the output to a new .avi file with sound.
Solution Make a full copy of the Check scene you created in this chapter, and name the new scene Checkmate. Edit the text and adjust the shape of the background plane appropriately. Add the new scene strip exactly as you did the Check strip, and position the strip in the appropriate place. Add the Alpha Over strip in the same way you did in the example in the chapter. In the Encoding panel in the Render properties, select Xvid as the video codec and MP3 as the audio.
Incorporate content directly from 3D or composited scenes into your videos. You can incorporate both animated scenes from the 3D viewport and composited scenes from the node system directly into the VSE, resulting in an extraordinarily powerful and integrated compositing and editing system.
Master It Use the output of the green screen compositing exercise from Chapter 4 in the VSE. Use a wipe to transition between the composited scene strip to another video strip. Render the output to the format of your choice.
Solution You can append the composited scene into a new .blend file by using the Append or Link option in the File menu, in the same way as you would any other datablock. Add the scene as a strip in the VSE as described in this chapter, by pressing the spacebar and selecting Scene. Add a separate video sequence, either one from the downloadable files from the website or one of your own, by pressing Shift+A and selecting Movie or Image depending on the video. Select the first and the second strips in order by using Shift+RMB, and then add a strip by pressing the spacebar and selecting Wipe. When you are ready to render, be sure Sequencer is activated in the Post Production panel in the Render properties area, and then select your preferred output format and press Animation to render the video. An example of a movie created in this way is in the comp_seq.mov file on the website for this book.

Chapter 12: The Blender-Python Interpreter

Become familiar with the basics of the Python language. Python is a widely used language for scripting in many different application areas. It is known for its ease of use, readability, and speed of development.
Master It Make sure that you have a good reference handy for Python syntax. In this chapter, I listed several good books you should consider buying. Use a Google search to find some more good online resources to quickly look up Python operators and data types. Python has a number of great tools for working with data structures like strings, lists, and dictionaries. Read up on these, and learn how to work with list functions. What is the difference between the append() and extend() list functions? How can you reverse the ordering of a list?
Solution A Byte of Python by Swaroop C H has the additional benefit of being freely available online in a variety of convenient formats at . The official documentation pages at are also excellent references, containing almost everything you will need to know about the Python language and its syntax. The difference between append() and extend() is that append() takes a list as an argument and appends the contents of that list to the original list. The extend() function adds an element to the end of a list. If the argument to extend() is itself a list, that list is added as a single element to the end of the original list. The method for reversing a list is reverse().
Work with the Blender Python scripting environment. The simplest way to access Python directly is through the Python Console built into Blender. In this shell environment, you can execute individual commands and perform introspection on variables. Python can also be used by writing scripts in Blender’s text editor window and viewing the results in the System Console or Terminal.
Master It In this chapter, you learned that you cannot concatenate a string and an integer by using the + operator. Likewise, you cannot add a string numerically. In some cases, however, numerical data may be input (for example, in a form) as a string type. Study the references you searched for in the previous Master It exercise to learn about type casting in Python and find out how you would convert the string "5" into an integer that can be added to another.
Solution As you learned in the chapter, data types can be converted to strings with the str() function. Likewise, they can be converted to integers with the int() function. You can convert a string to add it to an integer by using this function as follows:
>>print 2 + int("5")  >>7
Understand fundamental features of Python syntax. Python is a powerful programming language with a variety of data types, control structure options, and useful built-in functions. Its characteristic features include its reliance on indentation to represent logical structure.
Master It Create a variable my_list and assign it the list [1,2,1,3,1,4]. Call the dir() function with this list as an argument. Which of the methods returned by dir() do you think would be the correct method for removing one of the elements from the list? Experiment with the methods you think would work, and try to get rid of the number 2 from the list, so the list becomes [1,1,3,1,4]. Which method do you think will return the number of times the number 1 appears in the list? Additionally, how can you use .__doc__ strings to inquire about what you think the right answer is?
Solution The methods remove() and count() are among the methods returned by dir() for a list. As their names suggest, these are the methods you want to use to remove an element or count the number of occurrences of an element in a list. We can check this hypothesis by calling a .__doc__ string on these individual items.
>>> my_list = [1,2,1,3,1,4]  >>> my_list.remove.__doc__  'L.remove(value) ~DH remove first occurrence of value.\nRaises ValueError if the value is not present.'  >>> my_list.count.__doc__  'L.count(value) -> integer ~DH return number of occurrences of value'
You can remove the 2 from the list described in the exercise and count the number of occurrences of the number 1 as follows:
>>> my_list.remove(2)  >>> print(my_list)  [1,1,3,1,4]  >>> my_list.count(1)  3

Chapter 13: Python Scripting for Blender

Edit and run interactive scripts in Blender. Blender has its own internal text editor that you can use to write scripts or commentary. The text editor features line numbering and color-coded syntax highlighting.
Master It Get accustomed to working with the Blender text editor. Open operator_simple.py from the Templates menu in the text editor header. Run the script with the System Console visible. The names of all the 3D objects in the scene will be output to the console. Edit one line of the script so that the script outputs the names of only selected objects to the console.
Solution The change should be made in the loop beginning on line 5. Selected objects are an attribute of the context. Therefore, line 5,
for ob in context.scene.objects:
should be changed to
for ob in context.selected_objects:
Become familiar with the Blender-Python API. If you code in Blender Python, the API will become your faithful companion. A large part of learning to script for Blender is becoming comfortable navigating the API.
Master It An important step in using the API is to read the API itself and figure out what its various modules and classes do. Look over the API now. Which class would you use if you wanted to work with a Text object in the 3D space? What method would you use to set the text string for this object?
Solution To learn the correct operator for this, simply add a Text 3D object to the scene and check the Info window (at the top of your workspace) to see the operator that was just called. In this case, it would be bpy.ops.object.text_add() (with corresponding arguments). Set the text string by assigning the string to bpy.data.objects['Text'].data.body, where Text is the name of the Text object.
Design your own GUI with an interactive script. Blender’s Python API includes tools for designing graphical user interfaces for your scripts that enable you to set parameters and execute commands interactively.
Master It Add a new property to the bouncing cone add-on that enables you to interactively adjust the number of vertices in the base of the cone. At present, there are 10 vertices. Make sure there is a reasonable minimum number of vertices, and remember that the value should be an integer.
Solution See the file vertex_count.blend in the downloadable files that accompany this book for the solution to this exercise.

Chapter 14: Creating Assets for the Blender Game Engine

Model, rig, and texture a 3D character for use in the Blender Game Engine. A simple, low-poly rigged character is ideal for experimenting with the game engine. Modeling, rigging, and animating in the Action Editor can all be done quickly and easily in Blender.
Master It The example described in the tutorial uses TexFace texturing and therefore cannot be illuminated in real time with lights in the game engine. Fix this by creating a Blender material with the same UV-mapped texture so the character can be illuminated with lights in the game engine.
Solution See the file character_mat.blend on the accompanying website for this book.
Create a simple game environment of a maze and a skybox by using texture mapping. Simple modeling, combined with some clever texturing tricks, is enough to create an interesting in-game environment. Baking textures to images is a great way to adapt Blender procedural effects to use in the game engine.
Master It Texture the walls and floor of your maze in an interesting way.
Solution See the game_objects.blend file on the website for hints.
Place objects in the game environment, and set options for materials and lighting in the game engine. Appending objects and groups to a .blend file is a crucial skill for managing 3D assets on any kind of nontrivial Blender project. Understanding how materials and lighting interact in the game engine will enable you to get exactly the look and atmosphere you’re after for your game or interactive environment.
Master It In this chapter, you appended the skybox and maze to the game and then resized them both to make them suitable to each other. Next, append the character to the scene as well. Use grouping to append the armature and mesh simultaneously. Resize the character appropriately, and remember to apply the new scale. Test your animated action with the new scale. If there are problems, recalculate the bone roll angles in Edit mode.
Solution See the game_objects.blend file on the website.

Chapter 15: Making Things Happen in the Game Engine

Control characters and scenes by using logic bricks. Interactive control in the Blender game engine is made possible by using the powerful logic brick system. With this system, you can use sensors, controllers, and actuators to trigger game events on a variety of types of input.
Master It In the chapter, you saw how to make the character walk forward and turn right. Set up a similar character that can turn left and walk backward as well.
Solution See the file game.blend on the website for this book for the full logic on the main character armature, including turning left and walking backward.
Use properties, messages, and states to create complex interactions. Like a full-powered programming language, the BGE logic brick system enables you to store and modify values in the form of properties, to set up communications between different logic bricks using messages, and to control which logic bricks are active at what times by using states. In this way, complex interactions are made possible, limited only by the graphical nature of the logic bricks.
Master It Set up logic so that the wizards change directions whenever they hit the character, as well as when they hit each other.
Solution The simplest way to do this is to simply add a property called bump on the character armature. The wizards already are set to change direction when they strike an object with this property, so adding it to the character will have this effect. Of course, its effect will appear only when the character is in the green-ball protected state, because the game will end on the collision otherwise.
Work with textures to create dynamic text and in-game 2D animations. Textures in the BGE can be used for a variety of interesting effects. Dynamic text whose content can be updated by logic bricks and in-game animations can be created by using specifically mapped textures with certain parameter settings.
Master It Use the method described in this chapter to create a 2D walk cycle animation. Use orthogonal renders of the character walk cycle you created in Chapter 9 and then put those renders together in a single image, using a 2D image-editing program such as Photoshop or GIMP. Map the image onto a plane in the game engine to create a walking 2D cutout character.
Solution See the image file and the .blend file in the texture walk directory on the website for this book for a solution to this assignment.
Incorporate sound effects into your game environment. Sounds can be controlled by Sound actuators similarly to other effects in the BGE. Special features exist to automatically control the sound on the basis of its distance from the camera.
Master It Browse the free sound files website and find some other interesting sound effects. Follow the steps in this chapter to add a new 3D sound to a moving object in the 3D space.
Solution See the file soundcube.blend for the completed results of the tutorial.

Chapter 16: Python Power in the Blender Game Engine

Replace multiple logic brick setups with a few lines of Python code. By using a Python script controller to coordinate your sensors and actuators, you can accomplish the same things as with logic bricks but much more efficiently and with much less clutter. For larger, complex projects, using Python makes it vastly easier to keep your logic organized.
Master It Add some more movements to the walking character from this chapter. Create a new action and implement it in the BGE with Python so that pressing the W key will make him wave.
Solution See the file character_wave.blend on the website for this book for a solution.
Use Python to create effects in the BGE that would not be possible using logic bricks alone. Not every possible game engine behavior is encoded in logic brick form. Setting an object’s location is a simple example of something that requires Python to do. More-complex operations requiring variables or data structures also require the power of a fully functional programming language like Python.
Master It Implement a Python script that makes the default cube follow the mouse around the viewport.
Solution See the file mouse_cube.blend on the website for this book for a solution.
Create unique game environments with sound effects and multiple viewports. Effects like real-time control of sound volume and split-screen views can help to make your interactive 3D environment more engaging and immersive. With Python, these effects are easy to achieve.
Master It Create an environment with one stationary object and another object that can be moved around similarly to the cube in the viewports example. Have the stationary object emit a sound such that the volume of the sound increases to one when the objects are at their closest together and decreases to zero as the objects get farther apart.
Solution See the file volume_objects.blend on the website for this book for a solution.
Назад: Chapter 16: Python Power in the Blender Game Engine
Дальше: Index

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