Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Game Development

368 Articles
article-image-using-spritefonts-board-based-game-xna-40
Packt
30 Sep 2010
10 min read
Save for later

Using SpriteFonts in a Board-based Game with XNA 4.0

Packt
30 Sep 2010
10 min read
  XNA 4.0 Game Development by Example: Beginner's Guide Create your own exciting games with Microsoft XNA 4.0 Dive headfirst into game creation with XNA Four different styles of games comprising a puzzler, a space shooter, a multi-axis shoot 'em up, and a jump-and-run platformer Games that gradually increase in complexity to cover a wide variety of game development techniques Focuses entirely on developing games with the free version of XNA Packed with many suggestions for expanding your finished game that will make you think critically, technically, and creatively Fresh writing filled with many fun examples that introduce you to game programming concepts and implementation with XNA 4.0 A practical beginner's guide with a fast-paced but friendly and engaging approach towards game development Read more about this book (For more resources on XNA 4.0, see here.) SpriteFonts Unlike a Windows Forms application, XNA cannot use the TrueType fonts that are installed on your computer. In order to use a font, it must first be converted into a SpriteFont, a bitmap based representation of the font in a particular size that can be drawn with the SpriteBatch.DrawString() command. Technically, any Windows font can be turned into a SpriteFont, but licensing restrictions on most fonts will prevent you from using them in your XNA games. The redistributable font package is provided by Microsoft to address this problem and give XNA developers a range of usable fonts that can be included in XNA games. Following are samples of each of the fonts included in the font package: Time for action – add SpriteFonts to Game1 Right click on the Fonts folder in the Content project in Solution Explorer and select Add | New Item. From the Add New Item dialog, select Sprite Font. Name the font Pericles36.spritefont. After adding the font, the spritefont file will open in the editor window. In the spritefont file, change <Fontname>Kootenay</Fontname> to <Fontname>Pericles</Fontname>. Change <Size>14</Size> to <Size>36</Size>. Add the following declaration to the Game1 class: SpriteFont pericles36Font; Update the LoadContent() method of the Game1 class to load spritefont by adding: pericles36Font = Content.Load<SpriteFont>(@"FontsPericles36"); What just happened? Adding a SpriteFont to your game is very similar to adding a texture image. Since both are managed by the Content Pipeline, working with them is identical from a code standpoint. In fact, SpriteFonts are really just specialized sprite sheets, similar to what we used for our game pieces, and are drawn via the same SpriteBatch class we use to draw our sprites. The .spritefont file that gets added to your project is actually an XML document containing information that the Content Pipeline uses to create the .XNB file that holds the bitmap information for the font when you compile your code. The .spritefont file is copied from a template, so no matter what you call it, the XML will always default to 14 point Kootenay. In steps 4 and 5, we will edit the XML to generate 36 point Pericles instead. Just as with a Texture2D, we declare a variable (this time a SpriteFont) to hold the Pericles 36 point font. The Load() method of the Content object is used to load the font. SpriteFonts and extended charactersWhen a SpriteFont is built by the Content Processor, it actually generates bitmap images for each of the characters in the font. The range of characters generated is controlled by the <CharacterRegions> section in the SpriteFont's XML description. If you attempt to output a character not covered by this range, your game will crash. You can avoid this by removing the HTML comment characters (<!--and -->) from around the <DefaultCharacter> definition in the XML file. Whenever an unknown character is output, the character defined in <DefaultCharacter> will be used in its place. Score display Displaying the player's score with our new SpriteFont is simply a matter of calling the SpriteBatch.DrawString() method. Time for action – drawing the score Add a new Vector2 to the declarations area of Game1 to store the screen location where the score will be drawn: Vector2 scorePosition = new Vector2(605, 215); In the Draw() method, remove "this.Window.Title = playerScore.ToString();" and replace the line with: ToString();" and replace the line with:spriteBatch.DrawString(pericles36Font, playerScore.ToString(), scorePosition, Color.Black); What just happened? Using named vectors to store things like text positions, allows you to easily move them around later if you decide to modify the layout of your game screen. It also makes code more readable, as we have the name scorePosition instead of a hard-coded vector value in the spriteBatch.DrawString() call. Since our window size is set to 800 by 600 pixels, the location we have defined above will place the score into the pre-defined score box on our background image texture. The DrawString() method accepts a font to draw with (pericles36Font), a string to output (playerScore.ToString()), a Vector2 specifying the upper left corner of the location to begin drawing (scorePosition), and a color for the text to be drawn in (Color.Black). ScoreZooms Simply drawing the player's score is not very exciting, so let's add another use for our SpriteFont. In some puzzle games, when the player scores, the number of points earned is displayed in the center of the screen, rapidly growing larger and expanding until it flies off of the screen toward the player. We will implement this functionality with a class called ScoreZoom that will handle scaling the font. Time for action – creating the ScoreZoom class Add a new class file called ScoreZoom.cs to the Game1 class. Add the following using directive to the top of the file: using Microsoft.Xna.Framework.Graphics; Add the following declarati ons to the ScoreZoom class: public string Text;public Color DrawColor;private int displayCounter;private int maxDisplayCount = 30;private float scale = 0.4f;private float lastScaleAmount = 0.0f;private float scaleAmount = 0.4f; Add the Scale read-only property to the ScoreZoom class: public float Scale{ get { return scaleAmount * displayCounter; }} Add a Boolean property to indicate when the ScoreZoom has finished displaying: public bool IsCompleted{ get { return (displayCounter > maxDisplayCount); }} Create a constructor for the ScoreZoom class: public ScoreZoom(string displayText, Color fontColor){ Text = displayText; DrawColor = fontColor; displayCounter = 0;} Add an Update() method to the ScoreZoom class: public void Update(){ scale += lastScaleAmount + scaleAmount; lastScaleAmount += scaleAmount; displayCounter++;} What just happened? The ScoreZoom class holds some basic information about a piece of text and how it will be displayed to the screen. The number of frames the text will be drawn for are determined by displayCounter and maxDisplayCount. To manage the scale, three variables are used: scale contains the actual scale size that will be used when drawing the text, lastScaleAmount holds the amount the scale was increased by during the previous frame, and scaleAmount determines the growth in the scale factor during each frame. You can see how this is used in the Update() method. The current scale is increased by both the lastScaleAmount and scaleAmount. lastScaleAmount is then increased by the scale amount. This results in the scale growing in an exponential fashion instead of increasing linearly by a scaleAmount for each frame. This will give the text a zooming effect as it starts growing slowly and then speeds up rapidly to fill the screen. Time for action – updating and displaying ScoreZooms Add a Queue object to the Game1 class to hold active ScoreZooms: Queue<ScoreZoom> ScoreZooms = new Queue<ScoreZoom>(); Add a new helper method to the Game1 class to update the ScoreZooms queue: private void UpdateScoreZooms(){ int dequeueCounter = 0; foreach (ScoreZoom zoom in ScoreZooms) { zoom.Update(); if (zoom.IsCompleted) dequeueCounter++; } for (int d = 0; d < dequeueCounter; d++) ScoreZooms.Dequeue();} In the Update() method, inside the case section for GameState.Playing, add the call to update any active ScoreZooms. This can be placed right before the case's break; statement: UpdateScoreZooms(); Add the following to the CheckScoringChain() method to create a ScoreZoom when the player scores. Add this right after the playerScore is increased: ScoreZooms.Enqueue(new ScoreZoom("+" + DetermineScore(WaterChain.Count).ToString(), new Color(1.0f, 0.0f, 0.0f, 0.4f))); Modify the Draw() method of the Game1 class by adding the following right before the SpriteBatch.DrawString() call which draws the player's score: foreach (ScoreZoom zoom in ScoreZooms){ spriteBatch.DrawString(pericles36Font, zoom.Text, new Vector2(this.Window.ClientBounds.Width / 2, this.Window.ClientBounds.Height / 2), zoom.DrawColor, 0.0f, new Vector2(pericles36Font.MeasureString(zoom.Text).X / 2, pericles36Font.MeasureString(zoom.Text).Y / 2), zoom.Scale, SpriteEffects.None, 0.0f);} What just happened? Since all ScoreZoom objects "live" for the same amount of time, we can always be certain that the first one we create will finish before any created during a later loop. This allows us to use a simple Queue to hold ScoreZooms since a Queue works in a first-in-first-out manner. When UpdateScoreZooms() is executed, the dequeueCounter holds the number of ScoreZoom objects that have finished updating during this cycle. It starts at zero, and while the foreach loop runs, any ScoreZoom that has an IsCompleted property of true increments the counter. When the foreach has completed, ScoreZooms.Dequeue() is run a number of times equal to dequeueCounter. Adding new ScoreZoom objects is accomplished in step 4, with the Enqueue() method. The method is passed a new ScoreZoom object, which is constructed with a plus sign (+) and the score being added, followed by a red color with the alpha value set to 0.4f, making it a little more than halfway transparent. Just as the SpriteBatch.Draw() method has multiple overloads, so does the SpriteBatch.DrawString() method, and in fact, they follow much the same pattern. This form of the DrawString() method accepts the SpriteFont (pericles36Font), the text to display, a location vector, and a draw color just like the previous call. For the draw location in this case, we use this.Window.ClientBounds to retrieve the width and height of the game window. By dividing each by two, we get the coordinates of the center of the screen. The remaining parameters are the same as those of the extended Draw() call we used to draw rotated pieces. After the color value is rotation, which we have set to 0.0f, followed by the origin point for that rotation. We have used the MeasureString() method of the SpriteFont class to determine both the height and width of the text that will be displayed and divided the value by two to determine the center point of the text. Why do this when there is no rotation happening? Despite what the order of the parameters might indicate, this origin also impacts the next parameter: the scale. When the scale is applied, it sizes the text around the origin point. If we were to leave the origin at the default (0, 0), the upper left corner of the text would remain in the center of the screen and it would grow towards the bottom right corner. By setting the origin to the center of the text, the scale is applied evenly in all directions: Just as with the extended Draw() method earlier, we will use SpriteEffects.None for the spriteEffects parameter and 0.0f for the layer depth, indicating that the text should be drawn on top of whatever has been drawn already. Adding the GameOver game state Now that we can draw text, we can add a new game state in preparation for actually letting the game end when the facility floods.
Read more
  • 0
  • 0
  • 1901

article-image-unity-3d-game-development-dont-be-clock-blocker
Packt
29 Sep 2010
9 min read
Save for later

Unity 3D Game Development: Don't Be a Clock Blocker

Packt
29 Sep 2010
9 min read
  Unity 3D Game Development by Example Beginner's Guide A seat-of-your-pants manual for building fun, groovy little games quickly Build fun games using the free Unity 3D game engine even if you've never coded before Learn how to "skin" projects to make totally different games from the same file – more games, less effort! Deploy your games to the Internet so that your friends and family can play them Packed with ideas, inspiration, and advice for your own game design and development Stay engaged with fresh, fun writing that keeps you awake as you learn Read more about this book (For more resources on Unity 3D, see here.) We've taken a baby game like Memory and made it slightly cooler by changing the straight-up match mechanism and adding a twist: matching disembodied robot parts to their bodies. Robot Repair is a tiny bit more interesting and more challenging thanks to this simple modification. There are lots of ways we could make the game even more difficult: we could quadruple the number of robots, crank the game up to a 20x20 card grid, or rig Unity up to some peripheral device that issues a low-grade electrical shock to the player every time he doesn't find a match. NOW who's making a baby game? These ideas could take a lot of time though, and the Return-On-Investment (ROI) we see from these features may not be worth the effort. One cheap, effective way of amping up the game experience is to add a clock. Apply pressure What if the player only has x seconds to find all the matches in the Robot Repair game? Or, what if in our keep-up game, the player has to bounce the ball without dropping it until the timer runs out in order to advance to the next level? In this article let's: Program a text-based countdown clock to add a little pressure to our games Modify the clock to make it graphical, with an ever-shrinking horizontal bar Layer in some new code and graphics to create a pie chart-style clock That's three different countdown clocks, all running from the same initial code, all ready to be put to work in whatever Unity games you dream up. Roll up your sleeves—it's time to start coding! Time for action – prepare the clock script Open your Robot Repair game project and make sure you're in the game Scene. We'll create an empty GameObject and glue some code to it. Go to GameObject | Create Empty. Rename the empty Game Object Clock. Create a new JavaScript and name it clockScript. Drag-and-drop the clockScript onto the Clock Game Object. No problem! We know the drill by now—we've got a Game Object ready to go with an empty script where we'll put all of our clock code. Time for more action – prepare the clock text In order to display the numbers, we need to add a GUIText component to the Clock GameObject, but there's one problem: GUIText defaults to white, which isn't so hot for a game with a white background. Let's make a quick adjustment to the game background color so that we can see what's going on. We can change it back later. Select the Main Camera in the Hierarchy panel. Find the Camera component in the Inspector panel. Click on the color swatch labeled Back Ground Color, and change it to something darker so that our piece of white GUIText will show up against it. I chose a "delightful" puce (R157 G99 B120). Select the Clock Game Object from the Hierarchy panel. It's not a bad idea to look in the Inspector panel and confirm that the clockScript script was added as a component in the preceding instruction. With the Clock Game Object selected, go to Component | Rendering | GUIText. This is the GUIText component that we'll use to display the clock numbers on the screen. In the Inspector panel, find the GUIText component and type whatever in the blank Text property. In the Inspector panel, change the clock's X position to 0.8 and its Y position to 0.9 to bring it into view. You should see the word whatever in white, floating near the top-right corner of the screen in the Game view.. Right, then! We have a Game Object with an empty script attached. That Game Object has a GUIText component to display the clock numbers. Our game background is certifiably hideous. Let's code us some clock. Still time for action – change the clock text color Double-click the clockScript. Your empty script, with one lone Update() function, should appear in the code editor. The very first thing we should consider is doing away with our puce background by changing the GUIText color to black instead of white. Let's get at it. Write the built-in Start function and change the GUIText color: function Start(){ guiText.material.color = Color.black;}function Update() {} Save the script and test your game to see your new black text. If you feel comfy, you can change the game background color back to white by clicking on the Main Camera Game Object and finding the color swatch in the Inspector panel. The white whatever GUIText will disappear against the white background in the Game view because the color-changing code that we just wrote runs only when we test the game (try testing the game to confirm this). If you ever lose track of your text, or it's not displaying properly, or you just really wanna see it on the screen, you can change the camera's background color to confirm that it's still there. If you're happy with this low-maintenance, disappearing-text arrangement, you can move on to the Prepare the clock code section. But, if you want to put in a little extra elbow grease to actually see the text, in a font of your choosing, follow these next steps. Time for action rides again – create a font texture and material In order to change the font of this GUIText, and to see it in a different color without waiting for the code to run, we need to import a font, hook it up to a Material, and apply that Material to the GUIText. Find a font that you want to use for your game clock. I like the LOLCats standby Impact. If you're running Windows, your fonts are likely to be in the C:WindowsFonts directory. If you're a Mac user, you should look in the LibraryFonts folder. Drag the font into the Project panel in Unity. The font will be added to your list of Assets. Right-click (or secondary-click) an empty area of the Project panel and choose Create | Material. You can also click on the Create button at the top of the panel. Rename the new Material to something useful. Because I'm using the Impact font, and it's going to be black, I named mine "BlackImpact" (incidentally, "Black Impact" is also the name of my favorite exploitation film from the 70s). Click on the Material you just created in the Project Panel. In the Inspector panel, click on the color swatch labeled Main Color and choose black (R0 G0 B0), then click on the little red X to close the color picker. In the empty square area labeled None (Texture 2D), click on the Select button, and choose your font from the list of textures (mine was labeled impact - font texture). At the top of the Inspector panel, there's a drop-down labeled Shader. Select Transparent/Diffuse from the list. You'll know it worked when the preview sphere underneath the Inspector panel shows your chosen font outline wrapped around a transparent sphere. Pretty cool! Click on the Clock Game Object in the Hierarchy panel. Find the GUIText component in the Inspector panel. Click and drag your font—the one with the letter A icon—from the Project panel into the parameter labeled Font in the GUIText component. You can also click the drop-down arrow (the parameter should say None (Font) initially) and choose your font from the list. Similarly, click-and-drag your Material—the one with the gray sphere icon—from the Project panel into the parameter labeled Material in the GUIText component. You can also click on the drop-down arrow (the parameter should say None (Material) initially) and choose your Material from the list. Just as you always dreamed about since childhood, the GUIText changes to a solid black version of the fancy font you chose! Now, you can definitely get rid of that horrid puce background and switch back to white. If you made it this far and you're using a Material instead of the naked font option, it's also safe to delete the guiText.material.color = Color.black; line from the clockScript. Time for action – what's with the tiny font? The Impact font, or any other font you choose, won't be very… impactful at its default size. Let's change the import settings to biggify it. Click on your imported font—the one with the letter A icon—in the Project panel. In the Inspector panel, you'll see the True Type Font Importer. Change the Font Size to something respectable, like 32, and press the Enter key on your keyboard. Click on the Apply button. Magically, your GUIText cranks up to 32 points (you'll only see this happen if you still have a piece of text like "whatever" entered into the Text parameter of the GUIText of the Clock Game Object component). What just happened - was that seriously magic? Of course, there's nothing magical about it. Here's what happened when you clicked on that Apply button: When you import a font into Unity, an entire set of raster images is created for you by the True Type Font Importer. Raster images are the ones that look all pixelly and square when you zoom in on them. Fonts are inherently vector instead of raster, which means that they use math to describe their curves and angles. Vector images can be scaled up any size without going all Rubik's Cube on you. But, Unity doesn't support vector fonts. For every font size that you want to support, you need to import a new version of the font and change its import settings to a different size. This means that you may have four copies of, say, the Impact font, at the four different sizes you require. When you click on the Apply button, Unity creates its set of raster images based on the font that you're importing.
Read more
  • 0
  • 0
  • 2922

article-image-building-complete-board-based-puzzle-game-microsoft-xna-40
Packt
25 Sep 2010
14 min read
Save for later

Building a Complete Board-based Puzzle Game with Microsoft XNA 4.0

Packt
25 Sep 2010
14 min read
  XNA 4.0 Game Development by Example: Beginner's Guide Create your own exciting games with Microsoft XNA 4.0 Dive headfirst into game creation with XNA Four different styles of games comprising a puzzler, a space shooter, a multi-axis shoot 'em up, and a jump-and-run platformer Games that gradually increase in complexity to cover a wide variety of game development techniques Focuses entirely on developing games with the free version of XNA Packed with many suggestions for expanding your finished game that will make you think critically, technically, and creatively Fresh writing filled with many fun examples that introduce you to game programming concepts and implementation with XNA 4.0 A practical beginner's guide with a fast-paced but friendly and engaging approach towards game development Read more about this book (For more resources on XNA 4.0, see here.) It was just another day at the bottom of the ocean until an explosion in one of the storage bays cracked the protective dome around Deep Sea Research Lab Alpha. Now the entire place is flooding, and the emergency pump system is a chaotic jumble of loose parts. Designing a puzzle game The Puzzler has always been a popular game genre. From old standbys like Tetris to modern crazes like Bejeweled, puzzle games are attractive to players because they do not require a long-term time investment or a steep learning curve. The game mechanic is the heart of any good puzzle game. This mechanic is usually very simple, with perhaps a few twists to keep the players on their toes. In Flood Control, the player will be faced with a board containing 80 pieces of pipe. Some will be straight pipes and some will be curved. The objective of the game is to rotate the pipes to form a continuous line to pump water from the left side of the board to the right side of the board. Completing a section of pipe drains water out of the base and scores points for the player, but destroys the pipes used. New pipes will fall into place for the player to begin another row. Time for action - set up the Flood Control project Open Visual Studio Express Edition (If it is already open, select Close Solution from the File menu so you are starting with an empty slate). In the Visual Studio window, open the File menu and select New Project... Under Project Type, make sure XNA Game Studio 4.0 is selected. Under Templates, select Windows Game (4.0). Name the project Flood Control. Click on OK. Right-click on Flood ControlContent (Content) in the Solution Explorer window and select Add | New Folder. Name the folder Textures. Add another folder under Flood ControlContent (Content) and name the folder Fonts. Download the 0669_02_GRAPHICPACK.zip file from the book's code download link and extract the files to a temporary folder. Back in Visual Studio, right-click on Textures in the Content project and click on Add | Existing Item. Browse to the folder where you extracted the 0669_02_GRAPHICPACK files and highlight all of them. Click on Add to add them to your project. What just happened? You have now set up a workspace for building Flood Control, and created a couple of folders for organizing game content. You have also imported the sample graphics for the Flood Control game into the project. Introducing the Content Pipeline The Flood ControlContent (Content) project inside Solution Explorer is a special kind of project called a Content Project. Items in your game's content project are converted into .XNB resource files by Content Importers and Content Processors. If you right-click on one of the image files you just added to the Flood Control project and select Properties, you will see that for both the Importer and Processor, the Content Pipeline will use Texture - XNA Framework. This means that the Importer will take the file in its native format (.PNG in this case) and convert it to a format that the Processor recognizes as an image. The Processor then converts the image into an .XNB file which is a compressed binary format that XNA's content manager can read directly into a Texture2D object. There are Content Importer/Processor pairs for several different types of content—images, audio, video, fonts, 3D models, and shader language effects files. All of these content types get converted to .XNB files which can be used at runtime. In order to see how to use the Content Pipeline at runtime, let's go ahead and write the code to read these textures into memory when the game starts: Time for action - reading textures into memory Double-click on Game1.cs in Solution Explorer to open it or bring it to the front if it is already open. In the Class Declarations area of Game1 (right below SpriteBatch spriteBatch;), add: Texture2D playingPieces;Texture2D backgroundScreen;Texture2D titleScreen; Add code to load each of the Texture2D objects at the end of LoadContent(): playingPieces = Content.Load<Texture2D>(@"TexturesTile_Sheet");backgroundScreen = Content.Load<Texture2D>(@"TexturesBackground");titleScreen = Content.Load<Texture2D>(@"TexturesTitleScreen"); What just happened? In order to load the textures from disk, you need an in-memory object to hold them. These are declared as instances of the Texture2D class. A default XNA project sets up the Content instance of the ContentManager class for you automatically. The Content object's Load() method is used to read .XNB files from disk and into the Texture2D instances declared earlier. One thing to note here is that the Load() method requires a type identifier, specified in angled brackets (< >), before the parameter list. Known in C# as a "Generic", many classes and methods support this kind of type specification to allow code to operate on a variety of data types. We will make more extensive use of Generics later when we need to store lists of objects in memory. The Load() method is used not only for textures, but also for all other kinds of content (sounds, 3D models, fonts, etc.) as well. It is important to let the Load() method know what kind of data you are reading so that it knows what kind of object to return. Sprites and sprite sheets As far as XNA and the SpriteBatch class are concerned, a sprite is a 2D bitmapped image that can be drawn either with or without transparency information to the screen. Sprites vs. TexturesXNA defines a "sprite" as a 2D bitmap that is drawn directly to the screen. While these bitmaps are stored in Texture2D objects, the term "texture" is used when a 2D image is mapped onto a 3D object, providing a visual representation of the surface of the object. In practice, all XNA graphics are actually performed in 3D, with 2D sprites being rendered via special configurations of the XNA rendering engine. The simple form of the SpriteBatch.Draw() call when drawing squares only needs three parameters: a Texture2D to draw, a Rectangle indicating where to draw it, and a Color to specify the tint to overlay onto the sprite. Other overloads of the Draw() method, however, also allow you to specify a Rectangle representing the source area within the Texture2D to copy from. If no source Rectangle is specified, the entire Texture2D is copied and resized to fit the destination Rectangle. OverloadsWhen multiple versions of the same method are declared with either different parameters lists or different return values, each different declaration is called an "overload" of the method. Overloads allow methods to work with different types of data (for example, when setting a position you could accept two separate X and Y coordinates or a Vector2 value), or leave out parameters that can then be assigned default values. By specifying a source Rectangle, however, individual pieces can be pulled from a large image. A bitmap with multiple sprites on it that will be drawn this way is called a "sprite sheet". The Tile_Sheet.png file for the Flood Control project is a sprite sheet containing 13 different sprites that will be used to represent the pieces of pipe used in the game. Each image is 40 pixels wide and 40 pixels high, with a one pixel border between each sprite and also around the entire image. When we call SpriteBatch.Draw() we can limit what gets drawn from our texture to one of these 40 by 40 squares, allowing a single texture to hold all of the playing piece images that we need for the game: The Tile_Sheet.png file was created with alpha-based transparency. When it is drawn to the screen, the alpha level of each pixel will be used to merge that pixel with any color that already occupies that location on the screen. Using this fact, you can create sprites that don't look like they are rectangular. Internally, you will still be drawing rectangles, but visually the image can be of any shape. What we really need now to be able to work with the playing pieces is a way to reference an individual piece, knowing not only what to draw to the screen, but what ends of the pipe connect to adjacent squares on the game board. Alpha blendingEach pixel in a sprite can be fully opaque, fully transparent, or partially transparent. Fully opaque pixels are drawn directly, while fully transparent pixels are not drawn at all, leaving whatever has already been drawn to that pixel on the screen unchanged. In 32-bit color mode, each channel of a color (Red, Green, Blue, and Alpha) are represented by 8 bits, meaning that there are 256 different degrees of transparency between fully opaque (255) and fully transparent (0). Partially transparent pixels are combined with the current pixel color at that location to create a mixed color as if the pixels below were being seen through the new color. Classes used in Flood Control While it would certainly be possible to simply pile all of the game code into the Game1 class, the result would be difficult to read and manage later on. Instead, we need to consider how to logically divide the game into classes that can manage themselves and help to organize our code. A good rule of thumb is that a class should represent a single thing or type of thing. If you can say "This object is made up of these other objects" or "This object contains these objects", consider creating classes to represent those relationships. The Flood Control game contains a game board made up of 80 pipes. We can abstract these pipes as a class called GamePiece, and provide it with the code it needs to handle rotation and provide the code that will display the piece with a Rectangle that can be used to pull the sprite off the sprite sheet. The game board itself can be represented by a GameBoard class, which will handle managing individual GamePiece objects and be responsible for determining which pieces should be filled with water and which ones should be empty. The GamePiece class The GamePiece class represents an individual pipe on the game board. One GamePiece has no knowledge of any other game pieces (that is the responsibility of the GameBoard class), but it will need to be able to provide information about the pipe to objects that use the GamePiece class. Our class has the following requirements: Identify the sides of each piece that contain pipe connectors Differentiate between game pieces that are filled with water and that are empty Allow game pieces to be updated Automatically handle rotation by changing the piece type to the appropriate new piece type Given one side of a piece, provide the other sides of the piece in order to facilitate determining where water can flow through the game board Provide a Rectangle that will be used when the piece is drawn, to locate the graphic for the piece on the sprite sheet Identifying a GamePiece While the sprite sheet contains thirteen different images, only twelve of them are actual game pieces (the last one is an empty square). Of the twelve remaining pieces, only six of them are unique pieces. The other six are the water-filled versions of the first six images. Each of the game pieces can be identified by which sides of the square contain a connecting pipe. This results in two straight pieces and four pieces with 90 degree bends in them. A second value can be tracked to determine if the piece is filled with water or not instead of treating filled pieces as separate types of pieces. Time for action - build a GamePiece class - declarations Switch back to your Visual C# window if you have your image editor open. Right-click on Flood Control in Solution Explorer and select Add | Class... Name the class GamePiece.cs and click on Add. At the top of the GamePiece.cs file, add the following to the using directives already in the class: using Microsoft.Xna.Framework.Graphics;using Microsoft.Xna.Framework; In the class declarations section, add the following: public static string[] PieceTypes = { "Left,Right", "Top,Bottom", "Left,Top", "Top,Right", "Right,Bottom", "Bottom,Left", "Empty"};public const int PieceHeight = 40;public const int PieceWidth = 40;public const int MaxPlayablePieceIndex = 5;public const int EmptyPieceIndex = 6;private const int textureOffsetX = 1;private const int textureOffsetY = 1;private const int texturePaddingX = 1;private const int texturePaddingY = 1;private string pieceType = "";private string pieceSuffix = ""; Add two properties to retrieve information about the piece: public string PieceType{ get { return pieceType; }}public string Suffix{ get { return pieceSuffix; }} What just happened? You have created a new code file called GamePiece.cs and included the using statements necessary to access the pieces of the XNA Framework that the class will use. Using DirectivesAdding the XNA Framework using directives at the top of the class file allows you to access classes like Rectangle and Vector2 without specifying their full assembly names. Without these statements, you would need Microsoft.Xna.Framework.Rectangle in your code every time you reference the type, instead of simply typing Rectangle. In the declarations area, you have added an array called PieceTypes that gives a name to each of the different types of game pieces that will be added to the game board. There are two straight pieces, four angled pieces, and an empty tile with a background image on it, but no pipe. The array is declared as static because all instances of the GamePiece class will share the same array. A static member can be updated at execution time, but all members of the class will see the same changes. Then, you have declared two integer constants that specify the height and width of an individual playing piece in pixels, along with two variables that specify the array index of the last piece that can be placed on the board (MaxPlayablePieceIndex) and of the fake "Empty" piece. Next are four integers that describe the layout of the texture file you are using. There is a one pixel offset from the left and top edge of the texture (the one pixel border) and a single pixel of padding between each sprite on the sprite sheet. Constants vs. Numeric literalsWhy create constants for things like PieceWidth and PieceHeight and have to type them out when you could simply use the number 40 in their place? If you need to go back and resize your pieces later, you only need to change the size in one place instead of hoping that you find each place in the code where you entered 40 and change them all to something else. Even if you do not change the number in the game you are working on, you may reuse the code for something else later and having easily changeable parameters will make the job much easier. There are only two pieces of information that each instance of GamePiece will track about itself—the type of the piece and any suffix associated with the piece. The instance members pieceType and pieceSuffix store these values. We will use the suffix to determine if the pipe that the piece represents is empty or filled with water. However, these members are declared as private in order to prevent code outside the class from directly altering the values. To allow them to be read but not written to, we create a pair of properties (pieceType and pieceSuffix) that contain get blocks but no set blocks. This makes these values accessible in a read-only mode to code outside the GamePiece class.
Read more
  • 0
  • 0
  • 4156
Visually different images

article-image-introduction-game-development-using-unity-3d
Packt
24 Sep 2010
9 min read
Save for later

Introduction to Game Development Using Unity 3D

Packt
24 Sep 2010
9 min read
  Unity 3D Game Development by Example Beginner's Guide A seat-of-your-pants manual for building fun, groovy little games quickly Read more about this book (For more resources on this subject, see here.) Technology is a tool. It helps us accomplish amazing things, hopefully more quickly and more easily and more amazingly than if we hadn't used the tool. Before we had newfangled steam-powered hammering machines, we had hammers. And before we had hammers, we had the painful process of smacking a nail into a board with our bare hands. Technology is all about making our lives better and easier. And less painful. Introducing Unity 3D Unity 3D is a new piece of technology that strives to make life better and easier for game developers. Unity is a game engine or a game authoring tool that enables creative folks like you to build video games. By using Unity, you can build video games more quickly and easily than ever before. In the past, building games required an enormous stack of punch cards, a computer that filled a whole room, and a burnt sacrificial offering to an ancient god named Fortran. Today, instead of spanking nails into boards with your palm, you have Unity. Consider it your hammer—a new piece of technology for your creative tool belt. Unity takes over the world We'll be distilling our game development dreams down to small, bite-sized nuggets instead of launching into any sweepingly epic open-world games. The idea here is to focus on something you can actually finish instead of getting bogged down in an impossibly ambitious opus. When you're finished, you can publish these games on the Web, Mac, or PC. The team behind Unity 3D is constantly working on packages and export opinions for other platforms. At the time of this writing, Unity could additionally create games that can be played on the iPhone, iPod, iPad, Android devices, Xbox Live Arcade, PS3, and Nintendo's WiiWare service. Each of these tools is an add-on functionality to the core Unity package, and comes at an additional cost. As we're focusing on what we can do without breaking the bank, we'll stick to the core Unity 3D program for the remainder of this article. The key is to start with something you can finish, and then for each new project that you build, to add small pieces of functionality that challenge you and expand your knowledge. Any successful plan for world domination begins by drawing a territorial border in your backyard. Browser-based 3D? Welcome to the future Unity's primary and most astonishing selling point is that it can deliver a full 3D game experience right inside your web browser. It does this with the Unity Web Player—a free plugin that embeds and runs Unity content on the Web. Time for action – install the Unity Web Player Before you dive into the world of Unity games, download the Unity Web Player. Much the same way the Flash player runs Flash-created content, the Unity Web Player is a plugin that runs Unity-created content in your web browser. Go to http://unity3D.com. Click on the install now! button to install the Unity Web Player. Click on Download Now! Follow all of the on-screen prompts until the Web Player has finished installing. Welcome to Unity 3D! Now that you've installed the Web Player, you can view the content created with the Unity 3D authoring tool in your browser. What can I build with Unity? In order to fully appreciate how fancy this new hammer is, let's take a look at some projects that other people have created with Unity. While these games may be completely out of our reach at the moment, let's find out how game developers have pushed this amazing tool to its very limits. FusionFall The first stop on our whirlwind Unity tour is FusionFall—a Massively Multiplayer Online Role-Playing Game (MMORPG). You can find it at fusionfall.com. You may need to register to play, but it's definitely worth the extra effort! FusionFall was commissioned by the Cartoon Network television franchise, and takes place in a re-imagined, anime-style world where popular Cartoon Network characters are all grown up. Darker, more sophisticated versions of the Powerpuff Girls, Dexter, Foster and his imaginary friends, and the kids from Codename: Kids Next Door run around battling a slimy green alien menace. Completely hammered FusionFall is a very big and very expensive high-profile game that helped draw a lot of attention to the then-unknown Unity game engine when the game was released. As a tech demo, it's one of the very best showcases of what your new technological hammer can really do! FusionFall has real-time multiplayer networking, chat, quests, combat, inventory, NPCs (non-player characters), basic AI (artificial intelligence), name generation, avatar creation, and costumes. And that's just a highlight of the game's feature set. This game packs a lot of depth. Should we try to build FusionFall? At this point, you might be thinking to yourself, "Heck YES! FusionFall is exactly the kind of game I want to create with Unity, and this article is going to show me how!" Unfortunately, a step-by-step guide to creating a game the size and scope of FusionFall would likely require its own flatbed truck to transport, and you'd need a few friends to help you turn each enormous page. It would take you the rest of your life to read, and on your deathbed, you'd finally realize the grave error that you had made in ordering it online in the first place, despite having qualified for free shipping. Here's why: check out the game credits link on the FusionFall website: http://www.fusionfall.com/game/credits.php. This page lists all of the people involved in bringing the game to life. Cartoon Network enlisted the help of an experienced Korean MMO developer called Grigon Entertainment. There are over 80 names on that credits list! Clearly, only two courses of action are available to you: Build a cloning machine and make 79 copies of yourself. Send each of those copies to school to study various disciplines, including marketing, server programming, and 3D animation. Then spend a year building the game with your clones. Keep track of who's who by using a sophisticated armband system. Give up now because you'll never make the game of your dreams. Another option Before you do something rash and abandon game development for farming, let's take another look at this. FusionFall is very impressive, and it might look a lot like the game that you've always dreamed of making. This article is not about crushing your dreams. It's about dialing down your expectations, putting those dreams in an airtight jar, and taking baby steps. Confucius said: "A journey of a thousand miles begins with a single step." I don't know much about the man's hobbies, but if he was into video games, he might have said something similar about them—creating a game with a thousand awesome features begins by creating a single, less feature-rich game. So, let's put the FusionFall dream in an airtight jar and come back to it when we're ready. We'll take a look at some smaller Unity 3D game examples and talk about what it took to build them. Off-Road Velociraptor Safari No tour of Unity 3D games would be complete without a trip to Blurst.com—the game portal owned and operated by indie game developer Flashbang Studios. In addition to hosting games by other indie game developers, Flashbang has packed Blurst with its own slate of kooky content, including Off-Road Velociraptor Safari. (Note: Flashbang Studios is constantly toying around with ways to distribute and sell its games. At the time of this writing, Off-Road Velociraptor Safari could be played for free only as a Facebook game. If you don't have a Facebook account, try playing another one of the team's creations, like Minotaur China Shop or Time Donkey). In Off-Road Velociraptor Safari, you play a dinosaur in a pith helmet and a monocle driving a jeep equipped with a deadly spiked ball on a chain (just like in the archaeology textbooks). Your goal is to spin around in your jeep doing tricks and murdering your fellow dinosaurs (obviously). For many indie game developers and reviewers, Off-Road Velociraptor Safari was their first introduction to Unity. Some reviewers said that they were stunned that a fully 3D game could play in the browser. Other reviewers were a little bummed that the game was sluggish on slower computers. We'll talk about optimization a little later, but it's not too early to keep performance in mind as you start out. Fewer features, more promise If you play Off-Road Velociraptor Safari and some of the other games on the Blurst site, you'll get a better sense of what you can do with Unity without a team of experienced Korean MMO developers. The game has 3D models, physics (code that controls how things move around somewhat realistically), collisions (code that detects when things hit each other), music, and sound effects. Just like FusionFall, the game can be played in the browser with the Unity Web Player plugin. Flashbang Studios also sells downloadable versions of its games, demonstrating that Unity can produce standalone executable game files too. Maybe we should build Off-Road Velociraptor Safari? Right then! We can't create FusionFall just yet, but we can surely create a tiny game like Off-Road Velociraptor Safari, right? Well... no. Again, this article isn't about crushing your game development dreams. But the fact remains that Off-Road Velociraptor Safari took five supremely talented and experienced guys eight weeks to build on full-time hours, and they've been tweaking and improving it ever since. Even a game like this, which may seem quite small in comparison to full-blown MMO like FusionFall, is a daunting challenge for a solo developer. Put it in a jar up on the shelf, and let's take a look at something you'll have more success with.
Read more
  • 0
  • 0
  • 3963

article-image-blender-3d-249-quick-start
Packt
15 Sep 2010
9 min read
Save for later

Blender 3D 2.49: Quick Start

Packt
15 Sep 2010
9 min read
(For more resources on Blender, see here.) Interface One of the most important parts of any software is the interface, and with Blender, it is no different. But the Blender interface is unique, because it's all based on OpenGL graphics built in real-time that can be redesigned any way we want. Because of that, we can say that Blender has a default interface that can be customized any way we want. It's even possible to zoom all the items in menus and buttons. Let's take a look at the interface: (move cursor over image to enlarge) The default interface of Blender is divided into: 3D View: This is the section of the interface where you visualize all your objects and manipulate them. If you are in the modeling process, this window should always be visible. Buttons Window: Here we will find almost all the tools and menus, with options to set up features like modifiers, materials, textures, and lights. We can change the options available in this window with several small icons that change the buttons with specific tasks like materials, shading, editing, and others. Those buttons will reflect the active panel in Blender, for example, when we choose materials (F5 key). The Buttons window will then only show options related to materials. Header: All windows in Blender have a header, even if it's not visible at the time we create the window. The content of the header can change, depending on the window type. For example, in the header for the 3D View, we find options related to visualization, object manipulation, and selection. Menus: These menus work just like in any other application, with options to save files, import, and export models. Depending on the window type selected, the contents of the menu may differ. Scene Selector: We can create various scenes in Blender, and this selector allows us to choose and create these scenes. Because we will be modeling and dealing with scenery, the Scene selector will be an important tool for us. These parts make up the default interface of Blender, but we can change all aspects of the interface. There are even some modified screens, adapted to some common tasks with Blender, for us to choose. To access these modified screen sets, we must click on the selector located to the left of Scene Selector: There are screen sets prepared to work with Animation, Model, Material, Sequence, and Scripting. Each of these sets has a different interface organization, optimized for its specific task. A nice way to switch between these sets is with a keyboard shortcut, which is Ctrl plus left arrow or right arrow. Try this shortcut, and you will switch between sets very quickly. If you make any changes in the interface of Blender and want to overwrite the default interface, just press Ctrl + U, and your current interface will become the new default. In this way, every time Blender is started, your new interface will be shown. The same option can be reached in the File menu with the option named Save Default Settings. To restore the standard default interface, just use the option Load Factory Settings in the File menu. Windows and menus Blender has a lot of different windows that can do a lot of nice things. Two of the most common windows are the 3D View and the Buttons Window, but there are a lot more. With the Window type selector, we can choose among several types, such as File Browser, Text Editor, Timeline, and others. The Window type selector is always located in the left corner of each window, as shown in the following screenshot: Let's see what the function of each window is: Scripts Window: This window groups some nice scripts written in Python to add some extra tools and functionalities to Blender. It works much like plugins in other 3D Packages. There are scripts to help in a lot of different tasks like modeling, animation, and importing models. Some of these scripts are very helpful to architectural modeling such as Geom Tool and Bridge Faces. For instance, we can create a city space with only a few mouse clicks using a script named Discombobulator. In most cases, the scripts will appear in the right place in the Blender menus. Use this window only if you want to browse all scripts available in your Blender Scripts folder. To run a script, just select any script from the Scripts menu. File Browser: With this window, we can browse the files of a specific folder. This window appears automatically when we save or open a file. Image Browser: Here we can view the image files in a specific folder. This window is very useful to search for image files like .jpg, .png, and others. Node Editor and Compositing Nodes: With this window, it's possible to build node sets and create complex materials and textures. Buttons Window: We already have talked about this window, but it's nice to remember that after the 3D View, this is one of the most important windows, because here we can set options for almost any tool or functionality in Blender. This is the window responsible for several tools and functions in Blender, such as lights, materials, textures, and object properties. Outliner: This window shows us a list of the objects in your scene, and lists the relations among them. Here we can see if an object is related to some other object in a hierarchical way. In this window, we can easily hide and select objects, which may be useful for complex scenes. User Preferences: As the name suggests, here we can change Blender configurations, such as file paths, themes, Auto Save, and other options. Text Editor: This window allows us to write and open text files to make comments and place notes. We can open and run Python scripts here also. Audio Window: Here we can open and compose audio files in sequences. It works much like the Video Sequence Editor, but for audio files. Timeline: That's the place where we create animation. This window gives us nice tools to add key frames and build animations. Video Sequence Editor: Here we can build and composite images and video files. It's a very nice window that can replace a video editor in some ways. We can easily create a complex animation with a lot of shots and sequence them together with this window. And, we can use the Node Editor to create complex compositions and effects. UV/Image Editor: With this window, we can edit and set up images and textures. There is even a paint application, with which we can edit and make adjustments in textures and maps. This is a very important window for us, because a lot of the texture work we will be using will involve the use of UV Textures that require a lot of adjustments in the UV/Image Editor. NLA Editor: Here we can visualize and set up non-linear animations. This window is related more to animations and key frame visualization. A non-linear animation means that we can create small blocks of motions, which can be arranged any way we like, including copying and positioning those blocks into sequences. In Blender, these blocks are named strips. Because it's a non-linear editor, we can erase and rearrange the blocks without a break in the animation. For a linear animation system, any changes at the beginning of the animation would demand a full reconstruction of the animation from the artist. Action Editor: This window has nice options to set up actions related to character animation. Ipo Curve Editor: In this window, we can create and set up animations in a more visual way with curves. It's possible to add, edit, and delete key frames. Even for animations that don't require much work with characters and object deformations, like the ones we will be creating, it still requires a lot of work in the setup of curves to create good animation. Now we know what each of those windows do. Some of them will be very important for your visualization tasks, such as the Buttons and Scripts Window. Multiple windows A great feature in Blender is the ability to split the interface and use various window types at the same moment. The way to do this is very simple. We must right-click on the borders of an existing window to access a small menu with the options to split the window. We can split a window in two ways, which are vertical division and horizontal division. When you place the mouse cursor at the border of a window, the cursor will change into a double arrow. Just right-click and choose Split Area from the menu as shown in the next screenshot, and a division will be created: There are two kinds of divisions that we can create, which are vertical and horizontal divisions: Vertical: Click on the upper or lower border of a window to create a vertical division Horizontal: Click on the right or left border of a window to create a horizontal division After choosing Split Area, just place your mouse cursor where you wish the division to be created, and left-click with your mouse. Merge windows It's possible to merge two different windows too, with the same menu. There is an option named Join Areas, which will appear when we click with our right mouse button on the border of a window. After doing that, a big arrow will show which window will be destroyed and the arrow base shows the window that will take the place of the one destroyed: When you have chosen which windows should be joined, just left-click with your mouse to confirm it. We must always join windows that share the entire border with each other. Windows that only share a part of their borders can't be joined together, and we must find another way to join those windows.
Read more
  • 0
  • 0
  • 2491

article-image-blender-3d-249-working-textures
Packt
03 Sep 2010
9 min read
Save for later

Blender 3D 2.49: Working with Textures

Packt
03 Sep 2010
9 min read
(For more resources on Blender, see here.) Before we start to dig into textures, let me say that the biggest problem of working with them is actually finding or creating a good texture. That's why it's highly recommended that you start to create your own textures library as soon as possible. Textures are mostly image files, which represent some kind of surface, such as wood or stone, based on the photography. They work like wallpaper, which we can place on a surface or object. For instance, if we place an image of wood on a plane, it will give the impression that the plane is made of wood. That's the main principle of using textures; to make an object look like something in the real world. For some projects, we may need a special kind of texture, which won't be found in a common library, so we will have to take a picture ourselves or buy an image from someone. But don't worry, because often we deal with common surfaces that have common textures as well. Procedural textures vs. Non-procedural textures Blender basically has two types of textures, which are procedural textures and bitmap textures. Each one has positive and negative points; which one is the best? It will depend on your project needs: Procedural: This kind of texture is generated by the software at rendering time, just like vector lines in software, such as Inkscape or Illustrator. This means that it won't depend of any type of image file. The best thing about this type of texture is that being resolution-independent, we can set the texture to be rendered at high resolutions with minimum loss of quality. The negative point of this kind of texture is that it's harder to get realistic textures with it. The advantage of using procedural textures is that because they are all based on algorithms, they don't depend on a fixed number of pixels. Non-Procedural: To use this kind of texture, we will need an image file, such as a JPEG, PNG, or TGA file. The good thing about these textures is that we can quickly achieve a very realistic look and feel with it. On the other hand, we must find the texture file before using it. And what's more, if you are creating a high-resolution render, the texture file size must be as well. Texture library Do you remember the way we organized materials? We can do the exact same thing with textures. Besides setting names and storing the Blender files to import and use again later, collecting bitmap textures is another important point. Even if you don't start right away, it's important to know where to look for textures. So, here is a small list of websites, which provide free texture downloads: http://www.cgtextures.com http://blender-archi.tuxfamily.org/textures Applying textures To use a texture, we must apply a material to an object, and then use the texture with this material. We always use the texture inside a material. For instance, to make a plane that simulates a marble floor, we have to use a texture, and set up how the surface will react to light to give the surface a proper look of marble. To do that, we use the Texture panel, which is located right next to the Materials button. We can use a keyboard shortcut to open this panel; just hit F6 to open it: There is a way to add a texture in the Material panel also, with a menu named Texture: To get all the options, the best way to add a texture is with the Texture panel. In this panel, we will be able to see buttons, which represent the texture channels. Each one of these channels can hold a texture. The final texture will be a mix of all the channels. If we have a texture in channel 1 and another texture in channel 2, these textures will be blended and represented on the material. Before adding a new texture, we must select a channel by clicking on one of them. Usually the first channel will be selected, but if you want to use another one, just click on the channel. When the channel is selected, just click on the Add New button to add a new texture: The texture controls are very similar to the materials controls. We can give a name to the texture at the top and erase the texture if we don't want it anymore. With the selector, we can choose a previously created texture also. Just click and select it: Now, here comes the fun part. With a texture added, we have to choose a texture type. To do that, we click on the Texture Type combo box: There are a lot of textures, but most of them are procedural textures, and we won't use them frequently. The only texture that isn't procedural is the Image type. We see an example of a procedural Wood texture in the following screenshot: We can use textures such as Clouds and Wood to create effects and give surfaces a more complex look, or even create a grass texture with dirt on it. But most of the time, the texture type which we will be using will be the Image type: Each texture has it's own set of parameters to determine how it will look on the object. If we add a Wood texture, it will show the configuration parameters to the right: (Move the mouse over the image to enlarge.) If we choose texture type as Clouds, the parameters shown on the right will be completely different. With the Image texture type, it's not different. This kind of texture has its own type of setup. Following is the control panel: To show how to set up a texture, let's use an image file that represents a wood floor and a plane. We can apply the texture to this plane and set up how it's going to look, testing all parameters: The first thing to do is to assign a material to the plane, and then add a texture to this material. We choose the Image option as texture type. Blender will show the configuration options for this kind of texture. To apply the image as a texture to the plane, just click on the Load button, located in the Image menu. When we hit this button, we will be able to select the image file: Locate the image file, and the texture will be applied. If we want to have more control on how this texture is organized and placed on the plane, we need to learn how the controls work. Every time you make any changes to the setup of a texture, these changes will be shown in the preview window. Use it to make the required changes. Here is a list of what some of the buttons can do for the texture: UseAlpha: If the texture has an alpha channel, we have to press this button for Blender to calculate the channel. An image has an alpha channel when some kind of transparency is stored in the image. For instance, a PNG file with a transparent background has an alpha channel. We can use this to create a texture with a logo, for a bottle, or to add an image of a tree or person, to a plane. Rot90: With this option, we can rotate the texture by 90 degrees. Repeat: Every texture must be distributed on the object surface; repeating the texture in lines and columns is the default way to do that. Extend: If this button is pressed, the texture will be adjusted to fit the entire object surface area. Clip: With this option, the texture will be cropped, and we will be able to show only a part of it. To adjust which parts of the texture will be displayed, use the Min/Max X/Y options. Xrepeat / Yrepeat: This option determines how many times a texture is repeated with the repeat option turned on. Normal Map: If the texture will be used to create Normal Maps, press this button. These are textures used to change the face normals of an object. Still: With this button selected, we will specify that the image used as texture is a still image. This option is marked by default. Movie: If you want to use a movie file as texture, press this button. This is very useful if we need to make something similar to a theater projection screen or a tv screen. Sequence: We can use a sequence of images as a texture too. Just press this button. It works the same way as with a movie file. There are a few more parameters, such as the Reload button. If your texture file is updated outside of Blender, you must press this button to make Blender update the texture in your project. The X button can erase this texture; use it if you need to select another image file. When we add a texture to any material, an external link is created to this file. This link can be absolute or relative. Suppose we add a texture named wood.png, which is located in the root of your primary hard disk, such as C:. A link to this texture will be created like this — c:wood.png. So every time you open this file, the software will look for that file at that exact place. This is an absolute link, but we can use a relative link as well. For instance, when we add a texture located in the same folder as our scene, a relative link will be created. Every time we use an absolute link and we have to move the .blend file to another computer, the texture file must go with it. To imbue the image file with .blend, just press the icon for gift package: To save all the textures used in a scene, just access the File menu and use the Pack Data option. It will cause all the texture files to get embedded with the source .blend file.
Read more
  • 0
  • 0
  • 3085
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $15.99/month. Cancel anytime
article-image-designing-avatar-flash-multiplayer-virtual-worlds
Packt
27 Aug 2010
9 min read
Save for later

Designing an Avatar in Flash Multiplayer Virtual Worlds

Packt
27 Aug 2010
9 min read
(For more resources on Flash, see here.) Designing an avatar Avatar is very important in a virtual world because most of the features are designed around avatars. Users interact with each other via their avatars, they explore the virtual world via avatars, and they complete challenges to level up their avatars. An avatar is composited by graphics and animation. The avatar graphics are its looks. It is not a static image but a collection of images to display the directions and appearance. There are different approaches of drawing the avatar graphics depending on the render methods and how many directions and animations the avatar needs. Animations represent different actions of the avatar. The most basic animation is walking. Other animations such as hand waving and throwing objects are also common. There will be different animation sets for different virtual world designs. A fighting topic virtual world will probably contain a collection of fighting animation sets. A hunting topic virtual world will contain animations of collection items and using hunting tools. Determining the direction numbers of avatars' views Isometric tile is composed by diamond shapes with four-edge connection to the other tiles. It is not hard to imagine that every avatar in the isometric view may face towards four directions. They are the north east, south east, south west, and north west. However, sometimes using only these four directions may not be enough; some game designs may require the avatar to face the user or walk to the other isometric tile a cross the diamond corner. In this case, eight directions are required. The direction number of the avatars affects the artwork drawing directly. Just imagine that we are building a virtual world where players can fight with each other. How many animations are there for an avatar to fight? Say, five sets of animations. How many directions can the avatar faces? 4? 8? Or even 12? For example, we are now talking about five sets of animations with 8 directions of each avatar. That's already 40 animations for only one avatar. We may design the virtual world to have 12 kinds of avatars and each avatar to have different clothes for customization. The graphics workload keeps increasing when only one of these aspects increases. That's why I often consider different approaches that reduce the graphic workload of the avatars. Take four directions as an example. In most cases, we have very similar animations when the avatar is facing south-east and south-west. And the animation of north-east and north-west are similar too. Therefore, it is a common technique that mirrors the animation of west side into east side. It can be easily done in Flash by just changing the x-axis of the scaling property to between -1 and 1. This property results in the avatar flipping from one side to another side. For a 4-directions animation set, only 2 directions need to be drawn. In an 8-directions animation set, only 5 directions need to be drawn. Next, we will discuss the rendering methods that will conclude how the amount of directions, animations, and customization affect the graphic workload. Rendering avatars in Flash virtual world There are different approaches to render avatars in Flash virtual world. Each rendered method comes with both advantages and disadvantages. Some methods take more time to draw with fancy outlook while others may take more time to program. It is important to decide which rendering methods of the avatar are required in predevelopment stage. It will be much more difficult to change the rendering method after the project is in development. We will discuss different rendering methods and the pros and cons of them. Drawing an avatar using vector animation It is convenient to use the Flash native vector drawing for avatar because every drawing can be done within the Flash. The output can be cute and cartoon style. One advantage of using vector is that color customization is easy to implement by using the native ActionScript color transform. We can easily assign different colors to different parts of the avatar without extra graphic drawing. Another advantage of using vector animation is that we can scale up and down the avatars whenever needed. It is useful when we need to zoom in or out of the map and the avatars in the virtual world. The following graph shows the comparison of scaling up a vector and bitmap graphic: The disadvantage is that we need to draw the animation of every part of the avatar in every direction frame by frame. Flash tweening can help but the workload is heavier than other methods. We can prerender the animations or control them by ActionScript in methods discussed later. In vector animation, every animation is hand-drawn and thus any late modification on the avatar design can cost quite a lot of workload. There may not be too many directions of the avatars meaning the rotation of the avatars will not be very smooth. Rendering avatars using bitmap sprite sheet Sprite sheet is a graphics technique that is used in almost all game platforms. Sprite sheet is a large bitmap file that contains every frame of animation. Bitmap data from each frame is masked and rendered to the screen. A Flash developer may think that there is a timeline with frame one on the top left and counting the frame from left to right in each row from top to bottom. This technique is useful when the avatar graphic designer has experience in other game platforms. Another advantage of using bitmap data is faster rendering than vector in Flash player. The other advantage is the sprite sheet can be rendered from 3D software. For example, we can make an avatar model in Maya (http://autodesk.com/maya) or 3Ds Max (http://autodesk.com/3dsmax) with animations set up. Then we set up eight cameras with orthographic perspective. The orthographic perspective ensures the rendered image fits the isometric world. After setting up the scene, just render the whole animation with eight different cameras and we will get all the bitmap files of the avatar. The benefit is that the rendering process is automatic so that we can reduce the workload a lot. Later if we want to modify the character, we only need to modify it in the 3D software and render it again. One big disadvantage of using sprite sheet is the file size. The sprite sheets are in bitmap format and one set of animation can cost up to several hundred kilobytes. The file size can be very large when there are many animations and many more bitmaps for switching styles of the avatar. The other disadvantage is that changing color is quite difficult. Unlike vector rendering where color replacement can be done by ActionScript, we need to replace another bitmap data to change the color. That means every available color doubles the file size. Rendering avatars using real-time 3D engine We described how to use 3D software to prerender graphics of the avatars in the previous section. Instead of prerendering the graphics into 2D bitmap, we can integrate a Flash 3D engine to render the 3D model into isometric view in real time. Real-time 3D rendering is the next trend of Flash. There are several 3D engines available in the market that support rendering complex 3D models with animations. Papervision3D (http://blog.papervision3d.org/) and Away3D (http://away3d.com/) are two examples among them. The advantage of using 3D rendering in isometric is that the rotation of avatars can be very smooth. Also different textures can share the same model and different models can share the same animation skeleton. Thanks to this great graphic reusability, 3D rendering virtual world can create different combinations of avatar appearance and animations without adding extra graphic workload in development. However, one disadvantage of using 3D rendering is the Flash player performance. The latest version of Flash player is 10.1 at the time of writing. The following screenshots show that the CPU resources usage is very high when rendering the isometric 3D environment with three avatars on screen: Rendering avatars using 2D bone skeleton Bone skeleton used to be an uncommon method to render avatar. What it does is creates an animated skeleton and then glues different parts of body together onto the skeleton. It is somehow similar to the skeleton and mesh relationship in 3-D software but in two dimensions instead. A lot of mathematics is needed to calculate the position and rotation of each part of the body and make the implementation difficult. Thanks to the introduction of bone tool and inverse kinematics in Flash CS4, this technique is becoming more mature and easier to be used in the Flash world. Adobe has posted a tutorial about using bone tool to create a 2D character (http://www.adobe.com/devnet/flash/articles/character_animation_ik.html). The following screenshot shows another bone skeleton example from gotoAndPlay demonstrating how to glue the parts into a walking animation. The post can be found in this link: http://www.gotoandplay.it/_articles/2007/04/skeletal_animation.php The advantage of using 2D bone skeleton is that animations are controlled by ActionScript. The reusing of animations means this technique fits those game designs that require many animations. A dancing virtual world that requires a lot of different unique animations is one example that may need this technique. One disadvantage is that the large amount of mathematic calculation for the animations makes it difficult to implement. Every rendering methods has its own advantages and disadvantages and not one of the methods fits all type of games. It is the game designer's job to decide a suitable rendering method for a game or virtual world project. Therefore, it is important to know their limitations and consider thoughtfully before getting started with development. We can take a look at how other Flash virtual worlds render avatars by checking the showcase of the SmartFoxServer (http://www.smartfoxserver.com/showcase/).
Read more
  • 0
  • 0
  • 2971

article-image-customizing-avatar-flash-multiplayer-virtual-worlds
Packt
27 Aug 2010
5 min read
Save for later

Customizing an Avatar in Flash Multiplayer Virtual Worlds

Packt
27 Aug 2010
5 min read
(For more resources on Flash, see here.) Customizing your avatar A Flash virtual world is a social community in which players interact with each other and have their own identity. Virtual world usually lets a user decide the avatar's appearance by choosing the combination of different styles and colors. Customizing different styles Each part of the avatar will have different styles and shapes to form different combinations of the appearance of the avatar. Thanks to the timeline and movie clip features in Flash, we can put different styles of each part within the movie clip. For example, the following screenshot shows the head movie clip with different head styles placed frame by frame and we can use gotoAndStop to display the style we want. Customizing the color ActionScript supports changing the color transform for a given movie clip. It supports not only color tint but also applying color filter and detailed RGB transformation. We will use the simple color tint to change the color of the avatar. As the color transform is applying to the whole movie clip, we cannot simply tint the avatar movie clip because that will make the whole avatar tint to one solid color. In order to tint a partial part of the movie clip, we specifically create a movie clip in each part and name it color_area. We later program the ActionScript to change all movie clip names with color_area to the customized color. Adding customization to avatar class We are going to change the style and color by ActionScript in avatar class. We need to import the ColorTransform class in flash.geom package to change the color with ActionScript. import flash.geom.ColorTransform; We need several instance variables to hold the styles and color state. public const totalStyles:Number = 3;public var currentColor:Number = 0x704F4C;public var currentStyle:Number = 1; We wrap the whole block of color transform code into one function. The color transform adds RGB color transformation to the target movie clip. We only use colorTransform to tint the color here but it also supports percentage transform that adds partial color to the target movie clip. We will apply the color transform to the color area inside the head of the avatar in 4 directions. public function changeColor(newColor:Number = 0x000000):void { currentColor = newColor; for each(var avatar:MovieClip in _directionArray){ var avatarColor:ColorTransform = new ColorTransform(); avatarColor.color = newColor; avatar.head.color_area.transform.colorTransform = avatarColor; } } We modified the color by using color transform and used timeline to style the avatar style. Every frame in the head movie clip represents a style with its color tint area. We display the new style by changing the current frame of the avatar movie clip. It is also necessary to change the color again after switching the style because every style contains its own color area. public function changeStyle(styleNumber:int):void { for each(var avatar:MovieClip in _directionArray){ /* display the giving style in all parts of avatar*/ avatar.head.gotoAndStop(styleNumber); avatar.body.gotoAndStop(styleNumber); avatar.lefthand.gotoAndStop(styleNumber); avatar.righthand.gotoAndStop(styleNumber); /* need to apply the color again after changing the style */ var avatarColor:ColorTransform = new ColorTransform(); avatarColor.color = currentColor; avatar.head.color_area.transform.colorTransform = avatarColor; } currentStyle = styleNumber; } The purpose of the avatar class is to control the appearance of the avatar. We just implemented the direction, color, and style switching methods and it is now ready for customization panel to use. Designing a customization panel Avatars in virtual worlds and games often provide players with different kinds of customization. Some games allow users to customize the whole body with lots of options while some games may only provide two to three basic customizations. The layout design of the customization panel is often based on the number of options. There are two common customization panel layouts in the market. One layout displays arrows for a user to select next and previous styles. The other one displays a thumbnail view of the options within the same category. The arrows selection layout is suitable for an avatar that contains limited parts for customization. There may be only two to four categories and not many options in each category. Players can easily loop through different style combinations and choose their favorite one using this layout. The following avatar customization screenshot from the 2D Online RPG called Dragon Fable uses the arrows selection layout: The thumbnail view layout is suitable for avatars that can be highly customized. There are often many categories to customize and each category provides a lot of options for players to choose. Some virtual worlds even provide micro modification so that players can adjust details on the chosen style such as the distance between the eyes. Players do not need to iterate the large amount of styles and can quickly choose a style option among them with the thumbnail view. The following screenshot is an online Mii editor. Mii is the avatar system in the Nintendo Wii console. This is an online clone of the Mii avatar customization. It allows a large amount of avatar customization by the thumbnail view layout with extended features such as scaling and moving the elements.
Read more
  • 0
  • 0
  • 2658

article-image-advanced-effects-using-blender-particle-system
Packt
18 Aug 2010
6 min read
Save for later

Advanced Effects using Blender Particle System

Packt
18 Aug 2010
6 min read
(For more resources on Blender, see here.) The list above might be a bit daunting to some users but don't worry, I will discuss as much as I could (and bear with me when I ramble a lot) and hopefully I'll succeed in imbibing as much information as possible so when you're done reading this, you're proud to say: “I know Particle System!”, just like how Neo said in the Matrix: “I know Kung-Fu”. Unlike the previous articles that I've written before where I solely used one version of Blender through the entirety of the process, this time we might switch between the legacy Blender 2.4* and the recently-developed Blender 2.5*. The reason for this is that some Particle System features that we have been happily using in Blender 2.4* isn't merged yet in Blender 2.5*, making it unusable for the moment. I guess that is reasonable enough since Blender 2.5* is still undergoing heavy development and is still in beta stage. But who knows, maybe during this time of writing, it is already being developed or already is. So in line with that, here are the basic requirements for you to get going: Blender 2.49b (http://www.blender.org/download/get-blender/) Blender 2.53 (http://www.blender.org/development/release-logs/blender-250/) Basic Blender Particle System Knowledge (refer to http://www.packtpub.com/article/getting-started-with-blender-particle-system-1 for some info) lots and lots of patience! And just a bonus, we decided to provide you with the .blend files for all of our examples illustrated here. So hop on! Disintegration Effect The disintegration effect has been a common and very popular visual effect seen in feature movies, advertisements, and simply an eye candy. Often, it starts by having an object in its original and full form then after a while it will dissipate and disappear as though it was now made of dust. You can see this effect in one of the tests I did before here: http://vimeo.com/6763010. Much of the inspiration came from Daniel (aka NionsChannel in Youtube) who has really some nice effects on his list. The basic requirements for achieving this kind of effect are: a suitable particle system, highly subdivided mesh, and a force field. With that said, let's go ahead and start tinkering, shall we? Fire up Blender 2.49b and delete the default Cube (if any). (Move the mouse over the image to enlarge it.) (Deleting the Default Cube) Next, add or model the object of your choice. For purposes of this tutorial, let's add a simple UV Sphere with 256 Segments and 256 Rings, however, if your machine couldn't handle the high subdivision levels, you can lower it down to your liking. NOTE: The higher number of subdivisions you set, the finer and the more seamless the “shards” will be. Additionally, you can always go to Edit mode and press W > Subdivide to subdivide your mesh accordingly or adding a Subsurf modifier and applying it afterwards. The higher number of subdivisions you set, the finer and the more seamless the “shards” will be. Additionally, you can always go to Edit mode and press W > Subdivide to subdivide your mesh accordingly or adding a Subsurf modifier and applying it afterwards. (Adding a UV Sphere) (Highly Subdivided UV Sphere) After the UV Sphere has been added, proceed to Edit Mode and check over at the header the amount of faces it has. We'll use this as a base for the amount of particles that we'll be adding later on for the actual simulation. (UV Sphere Face Count) While in Edit Mode and all the vertices selected, press W then choose Set Smooth to smooth out the geometry shading. Now go back to Object Mode and proceed to Object (F7) in the Buttons Window then on the Particle Buttons, then click on Add New under Particle System tab to add a new particle system. (Adding a New Particle System) Rename the just-added particle system to something more relevant like “disintegration”. Then on the Amount input, we'll be changing the default 1000 to the number of faces our UV Sphere currently has (that's the reason we checked a while back in edit mode). So in this case, type in 65536. This will then correspond to one particle is equal to one face of our uv sphere. Next, change the End value to something shorter than 100 which is default. Let's try 40 for this example, which means all of the 65536 particles will be emitted within 40 frames. Basing from the default 25 frames per second rate, this would mean all those particles will be emitted in less than 2 seconds, which is what we want for this. Next is the Life value which we should be set to something longer as compared to the default 50 which is a little bit too early for our simulation. Let's set Life to 150; this will make our particles stay in our simulation area longer and not disappear earlier than expected. Under “Emit From:” panel, enable Random and Even then leave the other defaults as they are. Then finally, alter the values in the Physics tab and see which ones you are satisfied with. Check the screenshot below for some reference. (Particle System Settings) The next part is the icing on the cake, where we'll be adding a force field to generate the particle system's motion as though it was affected by real world effects like wind, turbulence, etc. With your cursor centered on your UV Sphere, add an Empty, name it “force”, and make sure the object rotation is cleared (ALT R) such that the local z-axis is oriented on the world z-axis. The UV Sphere and the Empty (“force”) should be in the same layer for the following effect to work. (Empty “force” Added) After adding our Empty object, we need to tell Blender how this object will affect our particle system. We'll do this by adding force values to this object. Forces in Blender act as external effectors for physics systems, which includes our particle system. You'll see what I mean in a while. Let's select the UV Sphere object and add a new Material Datablock to the object. (Adding a New Material to the Sphere) After adding a new material datablock, you can go ahead and tweak the material and shader settings the way you want to. Just like how I did mine (see screenshot): (Adding Material to the Sphere) With the Sphere still selected, head over to the Texture buttons under Shading (F5) and add a new texture slot. (Adding a New Texture) Next, choose Clouds as the Texture Type, increase the Noise Size and Noise Depth accordingly and just leave the Noise Basis to the default Blender Original, this will ensure a better distinction for the form that our particle system will exhibit later on. And the last but not the least, increase the Contrast of the texture, which will exaggerate the shape of our particle form later on. (Cloud Texture Settings)
Read more
  • 0
  • 0
  • 4649

article-image-advanced-effects-using-blender-particle-system-sequel
Packt
18 Aug 2010
6 min read
Save for later

Advanced Effects using Blender Particle System: A Sequel

Packt
18 Aug 2010
6 min read
(For more resources on Blender, see here.) Multiple Particle Systems Sometimes, singular particle systems are not enough to create the effects we want. This is when multiple particles come in, enabling us to create things like welding sparks, fireworks, rain splash, object shatters, etc. Thankfully, we have Reactor Particles which does just that. In most cases, reactor particles are born when other particle systems' events happen. You'll see more of that later in this part. I guess the best way to explain these things is through valid examples. Let's begin by simulating the fireworks effect we see during New Year or when there are festivities. First thing we need to do is to setup our scene. We'll be creating a very simple setup for now and it's up to you to take it further when needed. Fire up Blender 2.49 (sadly, Blender 2.5 doesn't support reactor particles yet) and orient the camera such that it is facing towards the positive y axis, as shown in the screenshot below: (Move the mouse over the image to enlarge it.) (Positioning the Camera) Next, delete the default Cube and add a Plane object then position it just below the camera's view. You can scale it according to your liking but we can also adjust it later on if need be. Let's name this plane “emitter”. (Plane Added in the Scene) With the “emitter” object still selected, go to Object (F7) then click on Particle buttons and add a new particle system. (Adding a New Particle System) This particle system will be the single burst that will eventually give birth to hundreds of particles later on. Let's name it “single” for easier reference later on. Keep the amount at a minimum, probably something like lower than 20, so it won't get too chaotic later on once the bursting of particles begin. Also change the Life of the particle system such that you see them die on your camera's view, otherwise we won't be able to see the bursting effect happening at all. And lastly, increase the Normal value under Physics, this will tell how the particles are shot and how fast. You might also have to edit the Life later on once you have decided on the Normal settings. (“single” Particle Settings) (Single Frame from the Particle System Animation) Now if we play back our animation, it should look something like this: (fireworks_1.avi) Next is the main particles for this system – the burst. With the plane emitter still selected, head over to the same window where the Particle System was created. On the upper right hand corner of the Particle System tab, you'll notice a portion there with “1 Part 1” on it with arrows left and right. These are indications of how many sub-particle systems there are in our main system. Our reaction particles would not act if it was a different system, so this is one crucial part. Where you see the 1 Part 1 area, click on the right arrow to register another sub-particle system, making it a “2 Part 2”. Then click on Add New again, just like how we did in the previous part. (Adding a Sub-Particle System) The important options that we have to take note here are the particle system type, emit from values, and target. With the Physics option, I'll leave it to you to tweak around. As you might have already guessed, we must first and foremost, choose Reactor as the particle system type, otherwise it would be useless doing so. Next is to change from which will the particles be emitted from (emit from), choose Particle since we wanted it to be emitted from the first particle system that we created. Then in the Target portion, you can choose from which system will it be emitted from, the default which is Psys:1, you can change this setting accordingly depending on which order you want it to be emitted. (Reactor Particle System Settings) Then here's the hardware rendered version of the system: (fireworks_2.avi) And that's about it! This is also applicable to things like welding sparks or rain splashes. If you want your particle reactor to happen on object collision, instead of setting the particle reactor to begin on Death, change it to Collision then set your objects as collision objects. You can check Part 1 of this article to see more on the material settings. And just a bonus, I've added some tiny details to particle system. You can check out the video below and also download the .blend file. (fireworks_3.avi) Boids Particle boids, are by far, one of the most underestimated and overlooked strengths of Blender's particle system. Not only is it very daunting at first, but the complexity it can offer you is mind blowing. Simply put, Particle Boid or Boids Particle System is a type of Particle Physics whereby it follows rules and protocols that a user has set. These rules may range from prey and predator relationships to advanced crowd simulation. They can be related to artificial intelligence in ways that each particle point can behave differently and act on its own regardless of the other particle points present in space. I don't, however, claim to have really surmounted boids particle systems, even before in earlier versions of Blender. It is so exciting and exhilirating yet frustrating at times. To fully comprehend it, you need lots and lots of patience, probably more time to tweak around, and a note near you to have the settings listed down. For the sake of this article, I'll keep this introduction to boids particle system as simple and as quick as possible, giving you more freedom to experiment and just give you a basic understanding on what this particle system is all about. Let's get going, shall we? Fire up Blender 2.53 and delete the default Cube in your scene. (Deleting the Default Cube) Next, we need to add the basic elements for our basic boids particle system. It includes 1) an emitter, 2) the visualization object, and 3) the goal object. With the cube deleted in our 3d viewport, add a plane object (or anything you wish) and leave the default levels of division as it is, this would act as our particle emitter. Name it “emitter”. (Plane Object Added) Next, add a simple UV Sphere above the plane, this would then act as our goal object. Smooth the shading and scale to something like 0.200. Name this uv sphere as “goal”.
Read more
  • 0
  • 0
  • 4320
article-image-flash-multiplayer-virtual-world-setting-smartfoxserver-third-party-http-and-database-s
Packt
17 Aug 2010
7 min read
Save for later

Flash Multiplayer Virtual World: Setting up SmartFoxServer with Third-party HTTP and Database Server

Packt
17 Aug 2010
7 min read
(For more resources on Flash, see here.) We are going to download and install Apache and MySQL server package. These kinds of server package features have easy install that auto-configures most of the server settings. It will also install some essential tool for beginners to manage the server easily, such as GUI server administration panel. Installing WAMP on Windows WampServer is an open source HTTP and database server solution on Windows. WAMP stands for Windows, Apache, MySQL, and PHP package. Go to http://www.wampserver.com/en/download.php. Click on Download WampServer to download the installer. Run the installer with all default settings. The server is configured and ready. The WampServer can run by launching from Start | Programs | WampServer | Start WampServer. It will be in the task bar and the server management operation can be found by clicking the WampServer icon. We can start the server by putting the server online in the menu. Installing MAMP on Mac OSX Similar to WampServer, MAMP is the one package web server solution that stands for Mac, Apache, MySQL, and PHP package. The MAMP package can be downloaded at http://www.mamp.info/. Download the MAMP package from the official website. Double-click on the downloaded MAMP dmg file to mount it. Drag the MAMP folder into the Applications folder. To run the MAMP server, go to Applications | MAMP and double-click on the MAMP.app. Installing LAMP on Linux As the same naming convention, the "L" stands for Linux here. Different Linux distributions use different ways to install applications. There may not be a oneclick install method on some Linux branch which requires us to install the Apache and MySQL individually. Some Linux may provide graphic user interface to install LAMP by just selecting it in the applications list. We will use Ubuntu to demonstrate the installation of LAMP. Launch terminal from Applications | Accessories | Terminal. Type following command to install LAMP. sudo tasksel install lamp-server The installer will progress and configure different modules. A dialog will prompt several times asking for a new MySQL root password. You can set your own MySQL password, while in the example we will leave the root password blank. After the completion of the installation, the MySQL server is set up as service in the system. It runs automatically and we do not need to manually launch it to use it. Connecting SmartFoxServer and MySQL server SmartFoxServer is a Java application and Java database connection driver is needed to connect from SmartFoxServer to MySQL database. Downloading JDBC Driver for MySQL JDBC is a Java database connection driver that we need to establish connections between the Java-based SmartFoxServer and the MySQL server. The JDBC driver for MySQL is called Connector/J. We are going to install it to enable MySQL connection from SmartFoxServer. Go to http://dev.mysql.com/downloads/connector/j/5.1.html in web browser. Download the Platform Independent Zip Archive. It may ask you to log in to MySQL.com account. Click on No thanks, just take me to the downloads! to bypass the login step. Choose a mirror to download by clicking on HTTP. Setting up the JDBC driver The MySQL Java connector comes with a bunch of files. We only need two among them. Extract the mysql-connector-java-5.1.10.zip file to a temporary folder. Open the folder and find the mysql-connector-java-5.1.10-bin.jar file. Copy that jar file into SmartFoxServer installation directory | jre | lib | ext. Go into the src directory of the extracted directory and copy the org directory to SmartFoxServer installation directory | jre | lib | ext. Configuring the server settings The configuration file of SmartFoxServer is an XML file that allows us to configure many server settings. It can configure the initial zone or room creation, server address, admin authorization, value tuning for performance, and a lot more. We are going to set the database connection for testing our setup in this article (core settings are out of scope of this article). The configuration file is called config.xml and is located in the SmartFoxServer installation directory under the Server directory. Configuring MySQL server connection in SmartFoxServer Open the config.xml in your favorite text editor. Go to line 203 of the config.xml. This line should be within the structure of a Zone tag with name as dbZone. Change the lines 203-218 from the config.xml: Original code: <DatabaseManager active="false"> <Driver>sun.jdbc.odbc.JdbcOdbcDriver</Driver> <ConnectionString>jdbc:odbc:sfsTest</ConnectionString> <!-- Example connecting to MySQL <Driver>org.gjt.mm.mysql.Driver</Driver> <ConnectionString>jdbc:mysql://192.168.0.1:3306/sfsTest </ConnectionString> --> <UserName>yourname</UserName> <Password>yourpassword</Password> <TestSQL><![CDATA[SELECT COUNT(*) FROM contacts]]></TestSQL> Replace the code in lines 203-218 with the following code: <DatabaseManager active="true"> <Driver>org.gjt.mm.mysql.Driver</Driver> <ConnectionString>jdbc:mysql://127.0.0.1:3306/mysql </ConnectionString> <UserName>root</UserName> <Password></Password> <TestSQL><![CDATA[SELECT NOW()]]></TestSQL> The new setting activates the DatabaseManager and configures the JDBC driver to the MySQL connector that we just downloaded. We also changed the user name and password of the connection to the database to "root" and empty password. We will use the empty password through out the development process but it is strongly recommended to set your own database user password. There is a TestSQL setting where we can write a simple database query so that the SmartFoxServer will try to run it to test if the database connection is correct. As we have not created any new databases for the virtual world, we will test the database connection by querying the current server time. Restarting the server We’ve just set up the connection between SmartFoxServer and third-party database. It is time to test the new setting by restarting the SmartFoxServer. To stop the SmartFoxServer in Windows and Linux, press Ctrl + C. To stop it in Mac OS X, click on the Cancel button in the SmartFoxServer log window. There is a log that appears as usual after we start up the server again. It is important to check the log carefully every time the config.xml is changed. The logfile can provide details of any errors that occur when it tries to load the configure file. For example, if we configure the database connection just now but forget to activate the DatabaseManager, the server will start up correctly. Then you may spend a lot of time debugging why the database connection is not working until you find that the DatabaseManager is not active at all. This happened to me several times while I was developing my first flash virtual world. If the server is running with the new database connection settings, the following lines will be appearing in the log. There can be different database manager settings for each zone. When checking the log, we should be aware which zone the log is referring to. We are configuring the database manager of dbZone zone now. DB Manager Activated ( org.gjt.mm.mysql.Driver ) Zone: dbZone If we forget to activate the DatabaseManager, we will not see the DB Manager Activated wording. Instead, the following message may appear in the log: DB Manager is not active in this Zone! Moreover, if the SmartFoxServer faces some fatal error on start up, it will terminate itself with more detailed error logs. The following lines are an example for error logs that appear when the MySQL connector file is missing: Can’t load db driver: org.gjt.mm.mysql.Driver [ Servre ] > DbManager could not retrive a connection. Java.sql.SQLException: Configuration file not found DbManagerException: The Test SQL statement failed! Please check your configuration. These lines state that the testing SQL failed to run, which we just set to test the connection. It also describes what exception has caused this error to help the debugging.
Read more
  • 0
  • 0
  • 2543

article-image-flash-multiplayer-virtual-world-smartfoxserver-using-embedded-web-server-and-database
Packt
16 Aug 2010
4 min read
Save for later

Flash Multiplayer Virtual World with SmartFoxServer Using Embedded Web Server and Database

Packt
16 Aug 2010
4 min read
(For more resources on Flash, see here.) Unlike a deployment environment, it is common to have just once machine acting both as server and client in a development environment. The machine will have SmartFoxServer, web server, and database installed. In this case, there are no noticeable differences between using the embedded or third-party web server and database. It is a good habit to simulate the deployment environment as much as possible in development stage. As we are going to use a third-party web server and database, we will set up a development environment that also uses the third-party server instead of the embedded web server and database in the third part of this article series. Installing Java Development Kit The Java Development Kit includes the essential development tools (JDK) and the Java Runtime Environment (JRE). The development tool compiles the Java source code into byte codes and the JRE is the response to execute the byte codes. We will need several Java compilations in later chapters. SmartFoxServer is build on the Java environment and we need the JRE to start up the server. The JDK and JRE may be pre-installed in some OSs. Installing JDK On Windows The steps for installing JDK on Windows are as follows: Go to http://java.sun.com/javase/downloads/. Click on the Download button of Java. It will lead to the Java SE Downloads page. Select Windows (or Windows x64 for 64-bits Windows) in Platform. Click on Download. If it prompts an optional login request, we can click the Skip this Step to bypass it. Launch the installer after the download. Install the Java Development Kit with all default settings. The Java environment is ready after installation completes. Installing JDK on Mac OSX The Mac OSX comes with its own set of Java environment. We can check the JDK and JRE version by following steps: Launch terminal from Applications | Utilities | Terminal. Type the following and press the Enter key: javac -version The command will output the currently installed version of the Java in the Mac OSX. In my case, it outputs: javac 1.6.0_17. The current version of SmartFoxServer at the time of writing recommends the version 1.6. If the Java is not updated, we can update it via Apple Menu | Software Update. The software update will check for any updates for your existing Mac software, including the Java environment. Installing JDK on Linux We can use the general method to download and install the JDK or use the system specific method to install the package. We will show the general method and the Ubuntu method. Installing for General Linux Go to http://java.sun.com/javase/downloads/index.jsp in browser. Click on the Download button. The platform Linux should be selected automatically. Otherwise, select Linux (or Linux x64 for 64-bit Linux). Click on Continue. If it prompts for login, click on Skip this Step to bypass it. For Redhat or Fedora Linux, choose the rpm-bin file to download. For other Linux, choose the .bin file to download. Launch terminal via Applications | Accessories | Terminal after the download completes. Change the directory to the folder that contains the downloaded package. The download destination varies from different profile settings. In my case, it is in Downloads folder. cd ~/Downloads/ The version is Java 6 Update 20 at the time of writing and the filename is jdk-6u20-linux-i586.bin or jdk-6u20-linux-i586-rpm.bin. Then we make it executable and launch the installer by the following commands: chmod a+x jdk-6u20-linux-i586.bin./jdk-6u20-linux-i586.bin The installer displays the license agreement. Type Yes at the end to agree and continue installation. Press the Enter key after the file’s extraction to end the installation. Installing for Ubuntu Linux Ubuntu users can install the JDK via the apt-get command. We will search for the latest package name of the JDK by the following command: apt-cache search --names-only sun-java.*-jdk The result shows the available JDK packet names. At the time of writing, it is JDK6: sun-java6-jdk - Sun Java(TM) Development Kit (JDK) 6 We use the apt-get command to install the JDK: sudo apt-get install sun-java6-jdk Type in the user password because it requires user’s password and the privilege to use apt-get.
Read more
  • 0
  • 0
  • 1707

article-image-developing-and-deploying-virtual-world-environment-flash-multiplayer
Packt
16 Aug 2010
7 min read
Save for later

Developing and Deploying Virtual World Environment for Flash Multiplayer

Packt
16 Aug 2010
7 min read
(For more resources on Flash, see here.) Comparing SmartFoxServer Lite, Basic, and Pro SmartFoxServer is a commercial product by gotoAndPlay(). There are three package options of SmartFoxServer. They are Lite version, Basic version, and Pro version. The demo license of the SmartFoxServer provides full features with 20 concurrent users maximum without time limitation. We will use the demo license to build the entire virtual world throughout the article. SmartFoxServer Lite The Lite version was the original SmartFoxServer since 2004. The maximum concurrent connection is limited to 50. It supports some core features like message passing, server-side user/room variables, and dynamic room creation. However, the lack of ActionScript 3.0greatly limits the performance and functionality. Moreover, it is being updated slowly so that many new features from Basic and Pro version are missing in Lite version. When we compare the version number of the three options, we will know that Lite version is developing at a slow pace. The version of SmartFoxServer Pro is 1.6.6 at the time of writing. The Basic version is 1.5.9 and the Lite version is only 0.9.1. Because of the slow update, not supporting ActionScript 3 and lack of features, it is not recommended to use Lite version in production. SmartFoxServer Basic SmartFoxServer Basic supports ActionScript 3 and a bunch of advanced features such as administration panel, game room spectators, and moderators. The administration panel lets moderators configure the zones, rooms, and users when the server is running. However, the lack of server-side extension support limits the customizability of the socket server. It also means that all logic must reside on the client side. This raises a security issue that the client may alter the logic to cheat. The Basic version provides enough features to build a Flash virtual world in small scale that does not require high security. If you need a specific server logic and room management or want to put logic in server side to prevent client-side cheating, Pro version is the choice. SmartFoxServer Pro There is a long list of features that are supported in Pro version. There are three features amongst all that distinguish the Pro version, they are: Server-side extension that modifies the server behavior JSON/Raw data protocol message passing Direct database connection Modifying the behavior of server Server-side extension is some server logic that developers can program to modify the default behavior of the internal event handler and add server-side functions to extend the server for specific usage. For example, we may want to override the "user lost" event so that we can save the user properties, telling others that someone is disconnected and something else. In this case, we can write a function in server-side extension to handle all these things when the user lost, instead of running the default behavior that was provided by SmartFoxServer. The SmartFoxServer is written in Java. Therefore the native support language of server-side extension is Java. In order to reduce the development difficulties, SmartFoxServer supports Python and ActionScript as a server-side extension. The support of ActionScript makes it much more convenient for most Flash developers to develop the server-side extension without even knowing Java. Please note that the version of ActionScript supported in server-side extension is ActionScript 1, instead of ActionScript 3. Take a look at the following code snippet on a server-side extension. The functions in server-side extensions are often similar to this one. It comes with arguments to know which user is calling this command at which room. In this snippet there is a command called getSomething and it will use the provided command parameters to get the result and return the result to the corresponding user. function handleRequest(cmd, params, user, fromRoom){ var response = {}; switch (cmd) { case "getSomething": var cpu = params['cpuType’]; response.something = "A Powerful Computer with CPU "+cpu; // send the response back to the client. _server.sendResponse(response,-1,null,[user]); break }} JSON/Raw data protocol JSON (http://www.json.org) is a light-weight text-based data-interchange format. It is designed for both humans and machines to read and write the data easily. For example, we can format a list of users and their information with the following JSON code. {"users": [ { "name" : "Steve", "level" : 12, "position" : { "x" : 6, "y" : 7 }, { "name" : "John", "level" : 5, "position" : { "x" : 26, "y" : 12 }} The default data protocol supported by SmartFoxServer Lite and Basic is XML. The Pro version added support of JSON and raw data protocol make it possible to compress the transfer of data between clients and server. The length of messages between clients and server is much shorter and it means the transmission speed is much faster. Take an example of a client sending data to a server with different protocols. We are now trying to fetch some data from the server, and this is what it looks like when sending a command to the server via different protocol. XML: <dataObj><var n=’name’ t=’s’>extension</var><var n=’cmd’t=’s’>getSomething</var><obj t=’o’ o=’param’><var n=’cpuType’t=’n’>8</var></obj></dataObj> The length of this command is 148 bytes. JSON: {"b":{"p":{"cpuType":8},"r":1,"c":"getSomething","x":"extension"},"t":"xt"} The length of this command is 75 bytes. Raw Data: %xt%extension%getSomething%8% The length of this command is 29 bytes. When comparing with the bytes used to send a command over the network, XML is two times the JSON and five times the raw protocol. We are talking about several byte differences that may not be considered in a broadband Internet. However, it is a must to consider every byte that was sent to the network because we are not talking about 29 bytes versus 148 bytes in the real applications. Imagine there are 2000 players in the virtual world, sending similar commands every second. We are now talking about 2.4Mbit/s versus 500Kbit/s, and this rough statistic already ignores those commands that fetch a long list of results, for example, a long list of items that are owned by the player. The raw protocol format takes less bytes to represent the command because it does not contain the field name of the data. All parameters are position-dependent. In the preceding command, the first parameter stands for an extension message and the second stands for the command name. Other command-specific parameters follow these two parameters. Raw protocol is position-dependent on the passing parameters while JSON is not. It is recommended to use JSON protocol in most case and use the raw data protocol in real-time interaction parts. Also, we should state clearly in comments code what each parameters stands for because others cannot get the field information from the raw data. Accessing the database directly Flash does not provide any database access functions. Flash applications always connect to database via server-side technique. The Pro version of SmartFoxServer provides direct database connectivity in server-side extension. The Flash virtual world will call a function in sever-side extension and it will handle the database connection for the Flash. As the database connectivity is handled in server-side extension, Basic and Lite version does not contain this handy feature. We have to wrap the database access in other server-side technique, such as PHP, to connect database in Basic and Lite version. The two graphs compare the architecture of the database access in SmartFoxServer Pro, Basic, and Lite.
Read more
  • 0
  • 0
  • 1327
article-image-ordering-buildings-flash-virtual-worlds
Packt
16 Aug 2010
2 min read
Save for later

Ordering the Buildings in Flash Virtual Worlds

Packt
16 Aug 2010
2 min read
(For more resources on Flash, see here.) Ordering the buildings The buildings are not well placed on the map. They overlap with each other in a very strange way. That is because we are now viewing the 3D isometric world in 2D screen with wrong ordering. When we view the 3D perspective in the following way, the closer objects should block the view of the objects behind. The buildings in the preceding image do not obey this real-world rule and cause some strange overlapping. We are going to solve this problem in the next section. Ordering the movie clips in Flash In Flash, every movie clip has its own depth. The depth is called z-order or the z-index of the movie clip. A movie clip with bigger z-order number is higher and covers the others with lower z-order when overlapping. By swapping their z-order, we can rearrange the movie clips on how they overlap and create the correct ordering of isometric buildings. Determining an object's location and view According to our tile-based isometric map, the object that locates in larger number of the x and y axis is in front of the object that locates in smaller number of the x and y axis. We can thus compare the isometric x and y coordinate to determine which object is in front. There is a special case when all shapes of the buildings occupy square shapes. In this situation, the order of the movie clip's z order can be easily determined by comparing their y position.
Read more
  • 0
  • 0
  • 1676

article-image-flash-10-multiplayer-game-game-interface-design
Packt
28 Jul 2010
10 min read
Save for later

Flash 10 Multiplayer Game: Game Interface Design

Packt
28 Jul 2010
10 min read
(For more resources on Flash and Games, see here.) Overview of Pulse library components The Pulse package includes two components Pulse.swc and PulseUI.swc.The Pulse.swc offers the API required for you to build a multiplayer game. While PulseUI offers the game screen management, both aid in the rapid development of your game. The Pulse.swc is required in order to communicate with the server and with other clients. The usage of PulseUI, on the other hand, is optional. It is recommended to use the PulseUI since it allows you to focus only on the game implementation and leaves the standard feature set of a multiplayer game to be taken care of by the PulseUI package. Once you have the implementation of your game done and working well, you can then replace the PulseUI package with something of your own that is more suited to your game. The following is a block diagram that shows the dependencies among different components: The Pulse API design The interaction of the game client with the server and other clients happens primarily via two classes that expose the Pulse features: GameClient GameClientCallback The GameClient is primarily used to send request to the server while creating a room, joining a room, or sending a message to other players such as chat or game state updates during game play. The GameClientCallback is an AS3 interface class for which one of the classes within the GameClient must implement. All notifications from the server are processed by the Pulse layer and corresponding notifications are called on the implementation of the callback class—for example, when a create room request was successful or when a chat message was received, etc. Creating the Hello World sample Let us now explore the Hello World sample that is included in the Pulse package. The Hello World sample and the rest of the samples rely heavily on the game screen management framework package, PulseUI, which is also included in the Pulse package along with the source code. In this article, we will focus on the code contained in the Hello World sample and how the sample makes use of the PulseUI. In order to explore the Hello World sample, we first need to create a project in Flash Builder—all the required source files already exists in the sample folders. The Hello World sample does the following: create a room or join an existing game room, then add, remove, or modify a game state—the changes done on one client instance are then reflected on all other clients that are in the same room. Think it is too much for a Hello World sample? It is not! These are just the basic functionalities for any multiplayer game. Moreover, we don't need to write the code for every bit of functionality because we heavily rely on Pulse SDK to do all the dirty work. Setting up the project Fire up the Flash Builder 4 IDE and let us start by creating an ActionScript project called Hello World: From the main menu, navigate to File | New | ActionScript Project. You will see the following screenshot. Enter a project name HelloWorld or any other name of your choice. Since we already have the entire source required for Hello World from the Pulse package, click on Next to specify that the source folder is already on the disk. This will bring up the following screen where we choose the Hello World src folder as shown. Note that the screenshot shows that Pulse was installed under F:Gamantra. This path may be different on your computer. Once we have chosen the source folder, we still need to choose the main source folder and main application file. Unfortunately, in order to do this, we need to navigate a bug in Flash Builder 4. You need to click on the Back button and then again on the Next button, bringing us back to where we were. We now click on the Browse button, as shown in the screenshot, and choose the [source path] src and click on OK. Next we choose the main application file—this determines the main class file that the execution will start with. We need to tell the Flash Builder to use the Pulse libraries for this project. In the Flash world, the library files come with an extension .swc, which stands for shockwave component. Once you make it available to your project, you can start using the classes and functions that are exposed from within the library. In order to do so, choose the Library Path tab view and click on the Add SWC… button; navigate to the lib folder within the Pulse installation folder and choose Pulse.swc and once again do the same procedure for PulseUI.swc. Click on the Finish button. As a final step, before attempting to run the sample, we also need to set the stage size to 800 (width) by 600 (height). The PulseUI requires the stage size to be exactly this size. We may also set the background color of our choice as shown in the following screenshot: After this step, Flash Builder 4 should be able to crunch all the code in folders and report no problems. This will also create the swf files under the project folder within the workspace ready for you to take it for a spin. At this point, you may also use the debugger to step through the code. But make sure the Pulse server is running so that you may login and explore all the screens. The Hello World specification The Hello World client will be able to create a new HelloGameState and share it with other players, and any player may change the x and y and have that change reflected in every player's screen. Here is the final screen that we will end up with: The screenshot is that of the game screen. The circles are a visual representation of the game states, the position of the circle comes from the corresponding game states x and y values and so does the color from the color property. We will have two buttons: one to add new game states and another to remove them. To add a new circle (a game state), we click on the Add button. To remove an existing game state, we click on any of the circles and click on the Remove button. The selected circle appears to be raised like the one on the far right-hand side of the screenshot. We may also modify an existing game state by moving the circles by clicking and dragging them to a different position—doing that on one client, we can observe the change in every other player's screen as well. The schema file For any Pulse-based game development, we first start out with an XML-formatted schema file. Let's now explore the schema file for the Hello World sample. The game developer must create a schema file that specifies all the needed game states, avatars, and game room objects. After you have created the schema file, we then use a Pulse modeler tool to create the class files based on the schema to be used within the game. So first let's examine the schema file for the Hello World project: <ObjectSchema> <import> <client import="pulse.gsrc.client.*" /> </import> <class name="HelloGameState" parent="GameState" classId="601" > <public> <property index="0" name="x" count="1" type="int"/> <property index="1" name="y" count="1" type="int"/> <property index="2" name="color" count="1" type="int"/> </public> </class></ObjectSchema> Navigate to the project folder where you have created the project and create a file called GameSchema.xml with the above content. We will not go through the details of the XML file in greater detail since it is out of the scope of this article. For the Hello World sample, we will define a game state object that we can use to share game states among all the players within a game room. We will name the class as HelloGameState, but you are welcome to call it by any name or something that makes sense to your game. You may also define as many game state classes as you like. For the HelloGameState in the schema file, each game state instance will define three properties, namely, x, y, and color. Code generator In order to create the AS3 class files from the schema file, you need to run the batch file called PulseCodeGen.bat found in the $bin folder. It takes the following three parameters: Path to schema file Namespace Output directory In order to make our life easier, let us create a batch file that will call the PulseCodeGen and pass all the required parameters. The reason for creating the batch file is that you have to code generate every time you modify the schema file. As you progress through your game implementation, it is normal to add a new class or modify an existing one. The convenience batch file may look like what's shown next. Let's call it .init.bat and save it in the same root folder for the sample along with the schema file. @ECHO OFFIF EXIST .srchwgsrcclient del .srchwgsrcclient*.asCALL "%GAMANTRA%"binPulseCodeGen.bat .GameSchema.xml hw.gsrc .srchwgsrcIF NOT %ERRORLEVEL% == 0 GOTO ERRORECHO Success!GOTO END:ERRORECHO oops!:ENDpause The schema file parameter to the Pulse code generator is specified as .GameSchema.xml because the schema file and the batch file are in the same folder. The second parameter is the package name for the generated classes—in this example, it is specified to be hw.gsrc. You specify the directory that the generated classes will be saved to as the last parameter. Note that the code generator appends client to both the package and directory into which it will be saved. It is also important to match the package name and directory structure as required by the AS3 compiler. Upon running the code gen successfully, there is one AS3 class generated for each class in the schema file and two additional supporting class files. One is a factory class called GNetClientObjectFactory, which is responsible for creating new instances of generated classes, and the other is GNetMetaDataMgr, which aids in serializing and de-serializing the transmitting data over the network. The data carried is what resides in the instances of generated classes. You don't need to deal with these two extra classes first hand; it is mostly used by the underlying Pulse runtime system. As for the generated classes for what is defined in the schema file, the name of the class would be identical to what is specified in the schema file plus the suffix Client. In this example, there would be a class generated with the name HelloGameStateClient.as. Go ahead and try running the batch file called init.bat under $samplesHelloWorld. Project directory structure The Hello World that is part of the Pulse package is organized into the following directory structure: hw gsrc client rsrc ui The package hw being the root package contains the main class HelloWorld.as, and the gsrc as you see contains the generated class. The rsrc folder contains the skin files, which we will discuss in more detail later in this article. The skin files in Pulse consist of three PNG files that provide all the basic buttons and background for the game. You can simply replace these PNG files with your own set, provided the individual elements with the file are of the exact dimensions and are placed at the exact same positions.
Read more
  • 0
  • 1
  • 2275