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 now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

How-To Tutorials - 3D Game Development

115 Articles
article-image-cryengine-3-breaking-ground-sandbox
Packt
23 Oct 2012
13 min read
Save for later

CryENGINE 3: Breaking Ground with Sandbox

Packt
23 Oct 2012
13 min read
The majority of games created using the CryENGINE SDK have historically been first-person shooters containing a mix of sandbox and directed gameplay. If you have gone so far as to purchase a book on the use of the CryENGINE 3 SDK, then I am certain that you have had some kind of idea for a game, or even improvements to existing games, that you might want to make. It has been my experience professionally that should you have any of these ideas and want to share or sell them, the ideas that are presented in a playable format, even in early prototype form, are far more effective and convincing than any PowerPoint presentation or 100-page design document. Reducing, reusing, recycling Good practice when creating prototypes and smaller scale games, especially if you lack the expertise in creating certain assets and code, is to reduce, reuse, and recycle. To break down what I mean: Reduce the amount of new assets and new code you need to make Reuse existing assets and code in new and unique ways Recycle the sample assets and code provided, and then convert them for your own uses Developing with CryEngine out of the box As mentioned earlier, the CryENGINE 3 SDK has a huge amount of out-of-the-box features for creating games. Let's begin by following a few simple steps to make our first game world. Before proceeding with this example, it's important to understand the features it is displaying; the level we will have created by the end of this article will not be a full, playable game, but rather a unique creation of yours, which will be constructed using the first major features we will need in our game. It will provide an environment in to which we can design gameplay. With the ultimate goal of this article being to create our own level with the core features immediately available to us, we must keep in mind that these examples are orientated to compliment a first-person shooter and not other genres. The first-person shooter genre is quite well defined as new games come out every year within this genre. So, it should be fairly easy for any developer to follow these examples. In my career, I have seen that you can indeed accomplish a good cross section of different games with the CryENGINE 3 SDK. However, the third- and first-person genres are significantly easier to create, immediately with the example content and features available right out of the box. For the designers: This article is truly a must-have for designers working with the engine. Though, I would highly recommend that all users of sandbox know how to use these features, as they are the principal features typically used within most levels of the different types of games in the CryENGINE. Time for action - creating a new level Let's follow a few simple steps to create our own level: Start the Editor.exe application. Select File | New. This will present you with a New Level dialog box that allows you to do the adjustments of some principal properties of your masterpiece to come. The following screenshot shows the properties available in New Level: Name this New Level, as Book_Example_1. The name that you choose here will identify this level for loading later as well as creating a folder and .cry file of the same name. In the Terrain section of the dialog box, set Heightmap Resolution to 1024x1024 , and Meters Per Unit to 1. Click on OK and your New Level will begin to load. This should occur relatively fast, but will depend on your computer's specifications. You will know the level has been loaded when you see Ready in the status bar. You will also see an ocean stretching out infinitely and some terrain slightly underneath the water. Maneuver your camera so that you have a good, overall view of the map you will create, as seen in the following screenshot: (Move the mouse over the image to enlarge.) What just happened? Congratulations! You now have an empty level to mold and modify at your will. Before moving on, let's talk a little about the properties that we just set, as they are fundamental properties of the levels within CryENGINE. It is important to understand these, as depending on the type of game you are creating, you may need bigger or smaller maps, or you may not even need terrain at all. Using the right Heightmap Resolution When we created the New Level, we chose a Heightmap Resolution of 1024x1024. To explain this further, each pixel on the heightmap has a certain grey level. This pixel then gets applied to the terrain polygons, and depending on the level of grey, will move the polygon on the terrain to a certain height. This is called displacement. Heightmaps always have varying values from full white to full black, where full white is maximum displacement and full black is minimum or no displacement. The higher the resolution of the heightmap, the more the pixels that are available to represent different features on the said heightmap. You can thus achieve more definition and a more accurate geometrical representation of your heightmap using higher resolutions. The settings can range from the smallest resolution of 128x128, all the way to the largest supported resolution of 8192x8192 . The following screenshot shows the difference between high resolution and low-resolution heightmaps: Scaling your level with Meters Per Unit If the Heightmap Resolution parameter is examined in terms of pixel size, then this dialog box can be viewed also as the Meters Per Pixel parameter. This means that each pixel of the heightmap will be represented by so many meters. For example, if a heightmap's resolution has 4 Meters Per Unit, then each pixel on the generated heightmap will measure to be 4 meters in length and width on the level. Even though Meters Per Unit can be used to increase the size of your level, it will decrease the fidelity of the heightmap. You will notice that attempting to smoothen out the terrain may be difficult since there will be a wider, minimum triangle size set by this value. Keep in mind that you can adjust the unit size even after the map has been created. This is done through the terrain editor, which we will discuss shortly. Calculating the real-world size of the terrain The expected size of the terrain can easily be calculated before making the map, because the equation is not so complicated. The real-world size of the terrain can be calculated as: (Heightmap Resolution) x Meters Per Unit = Final Terrain Dimensions. For example: (128x128) x 2m = 256x256m (512x512) x 8m = 4096x4096m (1024x1024) x 2m = 2048x2048m Using or not using terrain In most cases, levels in CryENGINE will use some amount of the terrain. The terrain itself is a highly optimized system that has levels of dynamic tessellation, which adjusts the density of polygons depending on the distance from the camera to the player. Dynamic tessellation is used to make the more defined areas of the terrain closer to the camera and the less defined ones further away, as the number of terrain polygons on the screen will have a significant impact on the performance of the level. In some cases, however, the terrain can be expensive in terms of performance, and if the game is made in an environment like space or interior corridors and rooms, then it might make sense to disable the terrain. Disabling the terrain in these cases will save an immense amount of memory, and speed up level loading and runtime performance. In this particular example, we will use the terrain, but should you wish to disable it, simply go to the second tab in the RollupBar (usually called the environment tab) and set the ShowTerrainSurface parameter to false, as shown in the following screenshot:   Time for action - creating your own heightmap You must have created a new map to follow this example. Having sufficiently beaten the terrain system to death through explanation, let's get on with what we are most interested in, which is creating our own heightmap to use for our game: As discussed in the previous example, you should now see a flat plane of terrain slightly submerged beneath the ocean. At the top of the Sandbox interface in the main toolbar, you will find a menu selection called Terrain; open this. The following screenshot shows the options available in the Terrain menu. As we want to adjust the terrain, we will select the Edit Terrain option. This will open the Terrain Editor window, which is shown in the following screenshot: (Move the mouse over the image to enlarge.) You can zoom in and pan this window to further inspect areas within the map. Click-and-drag using the right mouse button to pan the view and use the mouse wheel to zoom in and zoom out. The Terrain Editor window has a multitude of options, which can be used to manipulate the heightmap of your level. Before we start painting anything, we should first set the maximum height of the map to something more manageable: Click on Modify. Click on Set Max Height. Set your Max Terrain Height to 256. Note that the terrain height is measured in meters. Having now set the Max Height parameter, we are ready to paint! Using a second monitor: This is a good time to take advantage of a second monitor should you have one, as you can leave the perspective view on your primary monitor and view the changes made in the Terrain Editor on your second monitor, in real time. On the right-hand side of the Terrain Editor , you will see a rollout menu named Terrain Brush. We will first use this to flatten a section of the level. Change the Brush Settings to Flatten, and set the following values: Outside Radius = 100 Inside Radius = 100 Hardness = 1 Height = 20 NOTE: You can sample the terrain height in the Terrain Editor or the view port using the shortcut Control when the flatten brush is selected. Now paint over the top half of the map. This will flatten the entire upper half of the terrain to 20 meters in height. You will end up with the following screenshot, where the dark portion represents the terrain, and since it is relatively low compared to our max height, it will appear black: (Move the mouse over the image to enlarge.) Note that, by default, the water is set to a height of 16 meters. Since we flattened our terrain to a height of 20 meters, we have a 4-meter difference from the terrain to the water in the center of the map. In the perspective viewport, this will look like a steep cliff going into the water. At the location where the terrain meets the water, it would make sense to turn this into a beach, as it's the most natural way to combine terrain and water. To do this, we will smoothen the hard edge of the terrain along the water. As this is to become our beach area, let's now use the smooth tools to make it passable by the player: Change the Type of brush to Smooth and set the following parameters: Outside Radius = 50 Hardness = 1 I find it significantly easier to gauge the effects of the smooth brush in the perspective viewport. Paint the southern edge of the terrain, which will become our beach. It might be difficult to view the effects of the smooth brush simply in the terrain editor, so I recommend using the perspective viewport to paint your beach. Now that we have what will be our beach, let's sculpt some background terrain. Select the Rise/Lower brush and set the following parameters: Outside Radius = 75 Inside Radius = 50 Hardness = 0.8 Height = 1 Before painting, set the Noise Settings for the brush; to do so, check Enable Noise to true. Also set: Scale = 5 Frequency = 25 Paint the outer edges of the terrain while keeping an eye on the perspective viewport at the actual height of the mountain type structure that this creates. You can see the results in the Terrain Editor and perspective view, as seen in the following screenshots: (Move the mouse over the image to enlarge.) (Move the mouse over the image to enlarge.) It is a good time to use the shortcut to switch to smooth brush while painting the terrain. While in perspective view, switch to the smooth brush using the Shift shortcut. A good technique is to use the Rise/Lower brush and only click a few times, and then use Shift to switch to the smooth brush and do this multiple times on the same area. This will give you some nice terrain variation, which will serve us nicely when we go to texture it. Don't forget the player's perspective: Remember to switch to game mode periodically to inspect your terrain from the players level. It is often the case that we get caught up in the appearance of a map by looking at it from our point of view while building it, rather than from the point of view of the player, which is paramount for our game to be enjoyable to anyone playing it. Save this map as Book_Example_1_no_color.cry. What just happened? In this particular example, we used one of the three different techniques to create height maps within the CryENGINE sandbox: The first technique, which we performed here, was manually painting the heightmap with a brush directly in the sandbox. The second technique, which we will explore later, is generating procedural terrain using the tools provided in sandbox. Finally, the third technique is to import a previously created heightmap from another program. You now have a level with some terrain that looks somewhat like a beach, a flat land area, and some mountains. This is a great place to start for any outdoor map as it allows us to use some powerful out of the box engine features like the water and the terrain. Having the mountains surrounding the map also encourages the illusion of having more terrain behind it. Have a go hero – using additional brush settings With the settings we just explored, try to add some more terrain variation into the map to customize it further, as per your game's needs. Try using different settings for the brushes we explored previously. You could try adding some islands out in the water off the coast of your beach or some hills on the flat portion of the map. Use the Inside Radius and Outside Radius, which have a falloff of the brushes settings from the inner area having the strongest effect and the outer having the least. To create steeper hills or mountains, set the Inside Radius and Outside Radius to be relatively similar in size. To get a shallower and smoother hill set the Inside Radius and Outside Radius further apart. Finally, try using the Hardness, which acts like the pressure applied to a brush by a painter on canvas. A good way to explain this is that if the Hardness is set to 1, then within one click you will have the desired height. If set to 0.01, then it will take 100 clicks to achieve an identical result. You can save these variations into different .cry files should you wish to do so.
Read more
  • 0
  • 0
  • 2800

article-image-article-breaking-ground-with-sandbox
Packt
12 Oct 2012
11 min read
Save for later

Breaking Ground with Sandbox

Packt
12 Oct 2012
11 min read
What makes a game? We saw that majority of the games created on the CryENGINE SDK have historically been first-person shooters containing a mix of sandbox and directed gameplay. If you have gone so far as to purchase a book on the use of the CryENGINE 3 SDK, then I am certain that you have had some kind of idea for a game, or even improvements to existing games, that you might want to make. It has been my experience professionally that should you have any of these ideas and want to share or sell them, the ideas that are presented in a playable format, even in early prototype form, are far more effective and convincing than any PowerPoint presentation or 100-page design document. Reducing, reusing, recycling Good practice when creating prototypes and smaller scale games, especially if you lack the expertise in creating certain assets and code, is to reduce, reuse, and recycle. To break down what I mean: Reduce the amount of new assets and new code you need to make Reuse existing assets and code in new and unique ways Recycle the sample assets and code provided, and then convert them for your own uses Developing out of the box As mentioned earlier, the CryENGINE 3 SDK has a huge amount of out-of-the-box features for creating games. Let's begin by following a few simple steps to make our first game world. Before proceeding with this example, it's important to understand the features it is displaying; the level we will have created by the end of this article will not be a full, playable game, but rather a unique creation of yours, which will be constructed using the first major features we will need in our game. It will provide an environment in to which we can design gameplay. With the ultimate goal of this article being to create our own level with the core features immediately available to us, we must keep in mind that these examples are orientated to compliment a first-person shooter and not other genres. The first-person shooter genre is quite well defined as new games come out every year within this genre. So, it should be fairly easy for any developer to follow these examples. In my career, I have seen that you can indeed accomplish a good cross section of different games with the CryENGINE 3 SDK. However, the third- and first-person genres are significantly easier to create, immediately with the example content and features available right out of the box. For the designers:This article is truly a must-have for designers working with the engine. Though, I would highly recommend that all users of sandbox know how to use these features, as they are the principal features typically used within most levels of the different types of games in the CryENGINE. Time for action - creating a new level Let's follow a few simple steps to create our own level: Start the Editor.exe application. Select File | New. This will present you with a New Level dialog box that allows you to do the adjustments of some principal properties of your masterpiece to come. The following screenshot shows the properties available in New Level: Name this New Level, as Book_Example_1. The name that you choose here will identify this level for loading later as well as creating a folder and .cry file of the same name. In the Terrain section of the dialog box, set Heightmap Resolution to 1024x1024 , and Meters Per Unit to 1. Click on OK and your New Level will begin to load. This should occur relatively fast, but will depend on your computer's specifications. You will know the level has been loaded when you see Ready in the status bar. You will also see an ocean stretching out infinitely and some terrain slightly underneath the water. Maneuver your camera so that you have a good, overall view of the map you will create, as seen in the following screenshot: (Move the mouse over the image to enlarge.) What just happened? Congratulations! You now have an empty level to mold and modify at your will. Before moving on, let's talk a little about the properties that we just set, as they are fundamental properties of the levels within CryENGINE. It is important to understand these, as depending on the type of game you are creating, you may need bigger or smaller maps, or you may not even need terrain at all. Using the right Heightmap Resolution When we created the New Level, we chose a Heightmap Resolution of 1024x1024. To explain this further, each pixel on the heightmap has a certain grey level. This pixel then gets applied to the terrain polygons, and depending on the level of grey, will move the polygon on the terrain to a certain height. This is called displacement. Heightmaps always have varying values from full white to full black, where full white is maximum displacement and full black is minimum or no displacement. The higher the resolution of the heightmap, the more the pixels that are available to represent different features on said heightmap. You can thus achieve more definition and a more accurate geometrical representation of your heightmap using higher resolutions. The settings can range from the smallest resolution of 128x128, all the way to the largest supported resolution of 8192x8192 . The following screenshot shows the difference between high resolution and low resolution heightmaps:   Scaling your level with Meters Per Unit If the Heightmap Resolution parameter is examined in terms of pixel size, then this dialog box can be viewed also as the Meters Per Pixel parameter . This means that each pixel of the heightmap will be represented by so many meters. For example, if a heightmap's resolution has 4 Meters Per Unit, then each pixel on the generated heightmap will measure to be 4 meters in length and width on the level. Even though Meters Per Unit can be used to increase the size of your level, it will decrease the fidelity of the heightmap. You will notice that attempting to smoothen out the terrain may be difficult, since there will be a wider, minimum triangle size set by this value. Keep in mind that you can adjust the unit size even after the map has been created. This is done through the terrain editor, which we will discuss shortly. Calculating the real-world size of the terrain The expected size of the terrain can easily be calculated before making the map, because the equation is not so complicated. The real-world size of the terrain can be calculated as: (Heightmap Resolution) x Meters Per Unit = Final Terrain Dimensions. For example: (128x128) x 2m = 256x256m (512x512) x 8m = 4096x4096m (1024x1024) x 2m = 2048x2048m Using or not using terrain In most cases, levels in CryENGINE will use some amount of the terrain. The terrain itself is a highly optimized system that has levels of dynamic tessellation, which adjusts the density of polygons depending on the distance from the camera to the player. Dynamic tessellation is used to make the more defined areas of the terrain closer to the camera and the less defined ones further away, as the amount of terrain polygons on the screen will have a significant impact on the performance of the level. In some cases, however, the terrain can be expensive in terms of performance, and if the game is made in an environment like space or interior corridors and rooms, then it might make sense to disable the terrain. Disabling the terrain in these cases will save an immense amount of memory, and speed up level loading and runtime performance. In this particular example, we will use the terrain, but should you wish to disable it, simply go to the second tab in the RollupBar (usually called the environment tab) and set the ShowTerrainSurface parameter to false , as shown in the following screenshot:   Time for action - creating your own heightmap You must have created a new map to follow this example. Having sufficiently beaten the terrain system to death through explanation, let's get on with what we are most interested in, which is creating our own heightmap to use for our game: As discussed in the previous example, you should now see a flat plane of terrain slightly submerged beneath the ocean. At the top of the Sandbox interface in the main toolbar, you will find a menu selection called Terrain; open this. The following screenshot shows the options available in the Terrain menu. As we want to adjust the terrain, we will select the Edit Terrain option. This will open the Terrain Editor window, which is shown in the following screenshot: You can zoom in and pan this window to further inspect areas within the map. Click-and-drag using the right mouse button to pan the view and use the mouse wheel to zoom in and zoom out. The Terrain Editor window has a multitude of options, which can be used to manipulate the heightmap of your level. Before we start painting anything, we should first set the maximum height of the map to something more manageable: Click on Modify. Click on Set Max Height. Set your Max Terrain Height to 256. Note that the terrain height is measured in meters.     Having now set the Max Height parameter, we are ready to paint! Using a second monitor: This is a good time to take advantage of a second monitor should you have one, as you can leave the perspective view on your primary monitor and view the changes made in the Terrain Editor on your second monitor, in real time. On the right-hand side of the Terrain Editor , you will see a rollout menu named Terrain Brush. We will first use this to flatten a section of the level. Change the Brush Settings to Flatten, and set the following values: Outside Radius = 100 Inside Radius = 100 Hardness = 1 Height = 20     NOTE: You can sample the terrain height in the Terrain Editor or the view port using the shortcut Control when the flatten brush is selected. Now paint over the top half of the map. This will flatten the entire upper half of the terrain to 20 meters in height. You will end up with the following screenshot, where the dark portion represents the terrain, and since it is relatively low compared to our max height, it will appear black: Note that, by default, the water is set to a height of 16 meters. Since we flattened our terrain to a height of 20 meters, we have a 4-meter difference from the terrain to the water in the center of the map. In the perspective viewport, this will look like a steep cliff going into the water. At the location where the terrain meets the water, it would make sense to turn this into a beach, as it's the most natural way to combine terrain and water. To do this, we will smoothen the hard edge of the terrain along the water. As this is to become our beach area, let's now use the smooth tools to make it passable by the player: Change the Type of brush to Smooth and set the following parameters: Outside Radius = 50 Hardness = 1 I find it significantly easier to gauge the effects of the smooth brush in the perspective viewport. Paint the southern edge of the terrain, which will become our beach. It might be difficult to view the effects of the smooth brush simply in the terrain editor, so I recommend using the perspective viewport to paint your beach. Now that we have what will be our beach, let's sculpt some background terrain. Select the Rise/Lower brush and set the following parameters: Outside Radius = 75 Inside Radius = 50 Hardness = 0.8 Height = 1 Before painting, set the Noise Settings for the brush; to do so, check Enable Noise to true. Also set: Scale = 5 Frequency = 25 Paint the outer edges of the terrain while keeping an eye on the perspective viewport at the actual height of the mountain type structure that this creates. You can see the results in the Terrain Editor and perspective view, as seen in the following screenshots: It is a good time to use the shortcut to switch to smooth brush while painting the terrain. While in perspective view, switch to the smooth brush using the Shift shortcut. A good technique is to use the Rise/Lower brush and only click a few times, and then use Shift to switch to the smooth brush and do this multiple times on the same area. This will give you some nice terrain variation, which will serve us nicely when we go to texture it. Don't forget the player's perspective: Remember to switch to game mode periodically to inspect your terrain from the players level. It is often the case that we get caught up in the appearance of a map by looking at it from our point of view while building it, rather than from the point of view of the player, which is paramount for our game to be enjoyable to anyone playing it. Save this map as Book_Example_1_no_color.cry.
Read more
  • 0
  • 0
  • 1148

article-image-xna-4-3dgetting-battle-tanks-game-world
Packt
20 Sep 2012
16 min read
Save for later

XNA 4-3D:Getting the battle-tanks into game world

Packt
20 Sep 2012
16 min read
Adding the tank model For tank battles, we will be using a 3D model available for download from the App Hub website (http://create.msdn.com) in the Simple Animation CODE SAMPLE available at http://xbox.create.msdn.com/en-US/education/catalog/sample/simple_animation. Our first step will be to add the model to our content project in order to bring it into the game. Time for action – adding the tank model We can add the tank model to our project by following these steps: Download the 7089_06_GRAPHICSPACK.ZIP file from the book's website and extract the contents to a temporary folder. Select the .fbx file and the two .tga files from the archive and copy them to the Windows clipboard. Switch to Visual Studio and expand the Tank BattlesContent (Content) project. Right-click on the Models folder and select Paste to copy the files on the clipboard into the folder. Right-click on engine_diff_tex.tga inside the Models folder and select Exclude From Project. Right click on turret_alt_diff_tex.tga inside the Models folder and select Exclude From Project. What just happened? Adding a model to our game is like adding any other type of content, though there are a couple of pitfalls to watch out for. Our model includes two image files (the .tga files&emdash;an image format commonly associated with 3D graphics files because the format is not encumbered by patents) that will provide texture maps for the tank's surfaces. Unlike the other textures we have used, we do not want to include them as part of our content project. Why not? The content processor for models will parse the .fbx file (an Autodesk file format used by several 3D modeling packages) at compile time and look for the textures it references in the directory the model is in. It will automatically process these into .xnb files that are placed in the output folder &endash; Models, for our game. If we were to also include these textures in our content project, the standard texture processor would convert the image just like it does with the textures we normally use. When the model processor comes along and tries to convert the texture, an .xnb file with the same name will already exist in the Models folder, causing compile time errors. Incidentally, even though the images associated with our model are not included in our content project directly, they still get built by the content pipeline and stored in the output directory as .xnb files. They can be loaded just like any other Texture2D object with the Content.Load() method. Free 3D modeling software There are a number of freely available 3D modeling packages downloadable on the Web that you can use to create your own 3D content. Some of these include:   Blender: A free, open source 3D modeling and animation package. Feature rich, and very powerful. Blender can be found at http://www.blender.org. Wings 3D: Free, open source 3D modeling package. Does not support animation, but includes many useful modeling features. Wings 3D can be found at http://wings3d.com. Softimage Mod Tool: A modeling and animation package from Autodesk. The Softimage Mod Tool is available freely for non-commercial use. A version with a commercial-friendly license is also available to XNA Creator's Club members at http://usa.autodesk.com/adsk/servlet/pc/item?id=13571257&siteID=123112.         Building tanks Now that the model is part of our project, we need to create a class that will manage everything about a tank. While we could simply load the model in our TankBattlesGame class, we need more than one tank, and duplicating all of the items necessary to handle both tanks does not make sense. Time for action – building the Tank class We can build the Tank class using the following steps: Add a new class file called Tank.cs to the Tank Battles project. Add the following using directives to the top of the Tank.cs class file: using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; Add the following fields to the Tank class: #region Fields private Model model; private GraphicsDevice device; private Vector3 position; private float tankRotation; private float turretRotation; private float gunElevation; private Matrix baseTurretTransform; private Matrix baseGunTransform; private Matrix[] boneTransforms; #endregion Add the following properties to the Tank class: #region Properties public Vector3 Position { get { return position; } set { position = value; } } public float TankRotation { get { return tankRotation; } set { tankRotation = MathHelper.WrapAngle(value); } } public float TurretRotation { get { return turretRotation; } set { turretRotation = MathHelper.WrapAngle(value); } } public float GunElevation { get { return gunElevation; } set { gunElevation = MathHelper.Clamp( value, MathHelper.ToRadians(-90), MathHelper.ToRadians(0)); } } #endregion Add the Draw() method to the Tank class, as follows: #region Draw public void Draw(ArcBallCamera camera) { model.Root.Transform = Matrix.Identity * Matrix.CreateScale(0.005f) * Matrix.CreateRotationY(TankRotation) * Matrix.CreateTranslation(Position); model.CopyAbsoluteBoneTransformsTo(boneTransforms); foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect basicEffect in mesh.Effects) { basicEffect.World = boneTransforms[mesh.ParentBone. Index]; basicEffect.View = camera.View; basicEffect.Projection = camera.Projection; basicEffect.EnableDefaultLighting(); } mesh.Draw(); } } #endregion In the declarations area of the TankBattlesGame class, add a new List object to hold a list of Tank objects, as follows: List tanks = new List(); Create a temporary tank so we can see it in action by adding the following to the end of the LoadContent() method of the TankBattlesGame class: tanks.Add( new Tank( GraphicsDevice, Content.Load(@"Modelstank"), new Vector3(61, 40, 61))); In the Draw() method of the TankBattlesGame class, add a loop to draw all of the Tank objects in the tank's list after the terrain has been drawn, as follows: foreach (Tank tank in tanks) { tank.Draw(camera); } Execute the game. Use your mouse to rotate and zoom in on the tank floating above the top of the central mountain in the scene, as shown in the following screenshot: What just happened? The Tank class stores the model that will be used to draw the tank in the model field. Just as with our terrain, we need a reference to the game's GraphicsDevice in order to draw our model when necessary. In addition to this information, we have fields (and corresponding properties) to represent the position of the tank, and the rotation angle of three components of the model. The first, TankRotation, determines the angle at which the entire tank is rotated. As the turret of the tank can rotate independently of the direction in which the tank itself is facing, we store the rotation angle of the turret in TurretRotation. Both TankRotation and TurretRotation contain code in their property setters to wrap their angles around if we go past a full circle in either direction. The last angle we want to track is the elevation angle of the gun attached to the turret. This angle can range from 0 degrees (pointing straight out from the side of the turret) to -90 degrees (pointing straight up). This angle is stored in the GunElevation property. The last field added in step 3 is called boneTransforms, and is an array of matrices. We further define this array while defining the Tank class' constructor by creating an empty array with a number of elements equal to the number of bones in the model. But what exactly are bones? When a 3D artist creates a model, they can define joints that determine how the various pieces of the model are connected. This process is referred to as "rigging" the model, and a model that has been set up this way is sometimes referred to as "rigged for animation". The bones in the model are defined with relationships to each other, so that when a bone higher up in the hierarchy moves, all of the lower bones are moved in relation to it. Think for a moment of one of your fingers. It is composed of three distinct bones separated by joints. If you move the bone nearest to your palm, the other two bones move as well – they have to if your finger bones are going to stay connected! The same is true of the components in our tank. When the tank rotates, all of its pieces rotate as well. Rotating the turret moves the cannon, but has no effect on the body or the wheels. Moving the cannon has no effect on any other parts of the model, but it is hinged at its base, so that rotating the cannon joint makes the cannon appear to elevate up and down around one end instead of spinning around its center. We will come back to these bones in just a moment, but let's first look at the current Draw() method before we expand it to account for bone-based animation. Model.Root refers to the highest level bone in the model's hierarchy. Transforming this bone will transform the entire model, so our basic scaling, rotation, and positioning happen here. Notice that we are drastically scaling down the model of the tank, to a scale of 0.005f. The tank model is quite large in raw units, so we need to scale it to a size that is in line with the scale we used for our terrain. Next, we use the boneTransforms array we created earlier by calling the model's CopyAbsoluteBoneTransformsTo() method. This method calculates the resultant transforms for each of the bones in the model, taking into account all of the parent bones above it, and copies these values into the specified array. We then loop through each mesh in the model. A mesh is an independent piece of the model, representing a movable part. Each of these meshes can have multiple effects tied to it, so we loop through those as well, using an instance of BasicEffect created on the spot to render the meshes. In order to render each mesh, we establish the mesh's world location by looking up the mesh's parent bone transformation and storing it in the World matrix. We apply our View and Projection matrices just like before, and enable default lighting on the effect. Finally, we draw the mesh, which sends the triangles making up this portion of the model out to the graphics card. The tank model The tank model we are using is from the Simple Animation sample for XNA 4.0, available on Microsoft's MSDN website at http://xbox.create.msdn.com/en-US/education/catalog/sample/simple_animation. Bringing things down to earth You might have noticed that our tank is not actually sitting on the ground. In fact, we have set our terrain scaling so that the highest point in the terrain is at 30 units, while the tank is positioned at 40 units above the X-Z plane. Given a (X,Z) coordinate pair, we need to come up with a way to determine what height we should place our tank at, based on the terrain. Time for action – terrain heights To place our tank appropriately on the terrain, we first need to calculate, then place our tank there. This is done in the following steps: Add a helper method to the Terrain class to calculate the height based on a given coordinate as follows: #region Helper Methods public float GetHeight(float x, float z) { int xmin = (int)Math.Floor(x); int xmax = xmin + 1; int zmin = (int)Math.Floor(z); int zmax = zmin + 1; if ( (xmin < 0) || (zmin < 0) || (xmax > heights.GetUpperBound(0)) || (zmax > heights.GetUpperBound(1))) { return 0; } Vector3 p1 = new Vector3(xmin, heights[xmin, zmax], zmax); Vector3 p2 = new Vector3(xmax, heights[xmax, zmin], zmin); Vector3 p3; if ((x - xmin) + (z - zmin) <= 1) { p3 = new Vector3(xmin, heights[xmin, zmin], zmin); } else { p3 = new Vector3(xmax, heights[xmax, zmax], zmax); } Plane plane = new Plane(p1, p2, p3); Ray ray = new Ray(new Vector3(x, 0, z), Vector3.Up); float? height = ray.Intersects(plane); return height.HasValue ? height.Value : 0f; } #endregion In the LoadContent() method of the TankBattlesGame class, modify the statement that adds a tank to the battlefield to utilize the GetHeight() method as follows: tanks.Add( new Tank( GraphicsDevice, Content.Load(@"Modelstank"), new Vector3(61, terrain.GetHeight(61,61), 61))); Execute the game and view the tank, now placed on the terrain as shown in the following screenshot: What just happened? You might be tempted to simply grab the nearest (X, Z) coordinate from the heights[] array in the Terrain class and use that as the height for the tank. In fact, in many cases that might work. You could also average the four surrounding points and use that height, which would account for very steep slopes. The drawbacks with those approaches will not be entirely evident in Tank Battles, as our tanks are stationary. If the tanks were mobile, you would see the elevation of the tank jump between heights jarringly as the tank moved across the terrain because each virtual square of terrain that the tank entered would have only one height. In the GetHeight() method that we just saw, we take a different approach. Recall that the way our terrain is laid out, it grows along the positive X and Z axes. If we imagine looking down from a positive Y height onto our terrain with an orientation where the X axis grows to the right and the Z axis grows downward, we would have something like the following: As we discussed when we created our index buffer, our terrain is divided up into squares whose corners are exactly 1 unit apart. Unfortunately, these squares do not help us in determining the exact height of any given point, because each of the four points of the square can theoretically have any height from 0 to 30 in the case of our terrain scale. Remember though, that each square is divided into two triangles. The triangle is the basic unit of drawing for our 3D graphics. Each triangle is composed of three points, and we know that three points can be used to define a plane. We can use XNA's Plane class to represent the plane defined by an individual triangle on our terrain mesh. To do so, we just need to know which triangle we want to use to create the plane. In order to determine this, we first get the (X, Z) coordinates (relative to the view in the preceding figure) of the upper-left corner of the square our point is located in. We determine this point by dropping any fractional part of the x and z coordinates and storing the values in xmin and zmin for later use. We check to make sure that the values we will be looking up in the heights[] array are valid (greater than zero and less than or equal to the highest element in each direction in the array). This could happen if we ask for the height of a position that is outside the bounds of our map's height. Instead of crashing the game, we will simply return a zero. It should not happen in our code, but it is better to account for the possibility than be surprised later. We define three points, represented as Vector3 values p1, p2, and p3. We can see right away that no matter which of the two triangles we pick, the (xmax, zmin) and (xmin, zmax) points will be included in our plane, so their values are set right away. To decide which of the final two points to use, we need to determine which side of the central dividing line the point we are looking for lies in. This actually turns out to be fairly simple to do for the squares we are using. In the case of our triangle, if we eliminate the integer portion of our X and Z coordinates (leaving only the fractional part that tells us how far into the square we are), the sum of both of these values will be less than or equal to the size of one grid square (1 in our case) if we are in the upper left triangle. Otherwise our point is in the right triangle. The code if ((x - xmin) + (z - zmin) <= 1) performs this check, and sets the value of p3 to either (xmin, zmin) or (xmax, zmax) depending on the result. Once we have our three points, we ask XNA to construct a Plane using them, and then we construct another new type of object we have not yet used – an object of the Ray class. A Ray has a base point, represented by a Vector3, and a direction – also represented by a Vector3. Think of a Ray as an infinitely long arrow that starts somewhere in our world and heads off in a given direction forever. In the case of the Ray we are using, the starting point is at the zero point on the Y axis, and the coordinates we passed into the method for X and Z. We specify Vector3.Up as the direction the Ray is pointing in. Remember from the FPS camera that Vector3.Up has an actual value of (0, 1, 0), or pointing up along the positive Y axis. The Ray class has an Intersects() method that returns the distance from the origin point along the Ray where the Ray intersects a given Plane. We must assign the return value of this method to a float? instead of a normal float. You may not be familiar with this notation, but the question mark at the end of the type specifies that the value is nullable—that is, it might contain a value, but it could also just contain a null value. In the case of the Ray.Intersects() method, the method will return null if the object of Ray class does not intersect the object of the Plane class at any point. This should never happen with our terrain height code, but we need to account for the possibility. When using a nullable float, we need to check to make sure that the variable actually has a value before trying to use it. In this case, we use the HasValue property of the variable. If it does have one, we return it. Otherwise we return a default value of zero.
Read more
  • 0
  • 0
  • 3204

article-image-getting-started-gamesalad
Packt
20 Mar 2012
10 min read
Save for later

Getting Started with GameSalad

Packt
20 Mar 2012
10 min read
Let's get to it shall we?   System requirements In order for you to run GameSalad and create amazingly awesome games, you must meet the minimum system requirements, which are as follows:   Intel Mac (Any Mac from 2006 and above) Mac OS X 10.6 or higher At least 1GB RAM A device running iOS (iPad, iPhone 3G and up, or iPod Touch) If your computer exceeds these requirements, perfect! If not, you will need to upgrade your computer. Keep in mind, these are the minimum requirements, having a computer with better specs is recommended.   Let's get into GameSalad Let's start by downloading GameSalad and registering for an account. Let's go to GameSalad's website, www.gamesalad.com. Click the "Download Free App – GameSalad Creator" button.   While you are waiting for GameSalad to download, you should sign up for a free account. At the top of the page click Sign Up, enter your email address and create a username and password. You have two options for GameSalad membership, you can keep the Basic Pricing, which is completely free or select Professional Pricing. The difference is when you publish your App, you will have a Created with GameSalad splash screen, not a big deal right? Especially, not when you can get this awesome program for free! The Professional Pricing, which is $499 (USD) per year gives you all the features of the free version of GameSalad, plus it allows you to use iAds, Game Center, Promotional Links, your own Custom Splash Screen, and Priority Technical Support.   This does not include your Apple developer cost, which is $99 a year Other tools that are recommended for game development:   Adobe Photoshop (http://www.adobe.com/products/photoshop.html) or a free equivalent, Inkscape, Gimp, and Pixelmator Drawing Tablet (Makes creating sprites much easier but not required) Getting familiar with GameSalad's interface Once you open GameSalad, you are presented with several options on the screen.   Following are the options:   Home: It shows you the latest GameSalad links (Success stories, their latest game release, and so on...). News: It is self-explanatory, this shows you the latest update notes, and what is new in the GS community. Start: The getting started screen, here you have video tutorials, Wiki Docs, Blog, and more. Profile: This shows you, your GameSalad's profile page, messages, followers, and likes. New: These are all your new projects, Blank templates, and various bare bone templates to get you started. Recent: This shows you all of your recently saved projects. Portfolio: This shows all your published Apps through GameSalad.   Back/Forward buttons: Used when navigating back and forth between windows Web Preview: Allows you to see what your game will look like within the browser (HTML5) Home: This takes you right back to the project's main window Publish: Brings up the Publish window, here you can chose to deploy your game to the web, iPhone, iPad, Mac, or Android Scenes: Gives you a drop-down menu of all your scenes Feedback: Have some thoughts about GameSalad? Click this to send them to the Creators! Preview: At the main menu, or while editing an actor this starts your game from the beginning. If you are in a level, it will preview the level Help: Brings up the GameSalad documentation, which lists many help topics. Target Platform and Orientation: This drop-down menu gives you, your device options, iPhone Landscape, iPhone Portrait, GameSalad.com, iPad Landscape, iPad Portrait, and 720p HD Enable Resolution Independence (only when iPhone and iPad device is set): Check this option if you are creating a game specifically for the iPhone 4, 4S, iPad, or Kindles and Nooks. This takes your high resolution images and converts them for iPhone 3GS, 3G, and iPhone (1st Gen) Scenes Tab: Switch to this to see all your wonderful levels! Actors Tab: Select this tab to see all your actors in the game project. From this tab, you can group different types of actors, such as platforms and enemies. This comes in handy when an actor has to collide with numerous other actors (enemies or platforms) + button: Adds a Level - button (when a level is selected): Deletes a level Inspector (with Game selected) Actors: Here, you will see all your in-game items (Players, platforms, collectables, and so on) Attributes: Here, you can edit all the attributes of the game such as the display size. Devices: Here, you can edit all the settings for the mouse, touch screen, accelerometer, screen, and audio. Inspector (with Scene selected) o Attributes: Here, you can edit all the attributes of the current level, such as the size of the level, screen wrap (X,Y), Gravity, background color, camera settings, and autorotate. o Layers: Here, you can create numerous layers with scrollable on or off. For example, a layer called UI with scrollable deselected will have all your user interface items, and they will stay on the screen. Library (with Behaviors selected) o Standard: These are all the standard GameSalad behaviors (Movements, change actor attributes, and more) o Custom: These are your own custom behaviors. Let's say, you needed the same behavior throughout numerous actors but you didn't want to keep re-adding and changing the behavior for each actor. Once, you create the Behavior, drag it into this box and you can use it as much as you want. o Pro: These are all the professional behaviors (only available when you have paid for the professional membership). These include Game Center Connect, iAd, and Open URL Library (with Images selected) Project: This shows all your imported images into this project. Purchased: This is a new feature that shows the images you have purchased through GameSalad's Marketplace. (When you click Purchase Images..., this will take you to the GameSalad Marketplace where you will have a plethora of Content packs and more to purchase and import into your game) When you click the "+" button, you can import images from your hard drive, alternately, you can drag them directly into the Library from the Finder Library (with Sounds selected): This shows you all of your sound effects and music that you have imported into your project. As with images, when you click the "+" button you can import sound effects or music from your hard drive, or drag them directly in from the Finder. Actor Mode: This involves normal mouse functions; it allows you to select actors within the level. Following is the screenshot of the icon: Camera Mode: It allows you to edit the camera, position, and scrolling hot spots for characters that control the camera. Following is the screenshot of the icon: Reset Scene: While previewing your level and if this button is pressed, everything will go back to its initial state. Following is the screenshot of the icon: Play: This will start a preview of the current level. This is different from the green Project Preview button, as this will only preview the current level, and not the whole project. When you complete the level, an alert will appear telling you the scene has ended, and you can either select to preview the next level, or reset the current scene. Following is the screebshot of the icon: Show Initial State: If you have run a preview, and want to see the initial state without ending the preview, then pause the preview, click on the following icon and the initial state is seen. Following is the screenshot of the icon: For now, let's click New | My Great Project This is a fresh project; everything is empty. You can see that you have one level so far, but you can add more at a later time. See the Scenes and Actors Tabs? Currently, Scenes is selected, this shows you all of your levels, but if you click the Actors tab, you will be able to see all your actors (or game objects, characters, collectables, and so on.) in the game. You can also rearrange all of the actors in Actor Tags, to give you an idea of what these are useful for. Take for example, if you have 30 different enemies, when you are setting up your collisions within behaviors, you won't have to set up 30 different collisions. Rather, when you set up all the enemies within a tag named Enemies you can do a single collision behavior for all actors of the tag! This reduces a lot of time when coding. We will get into more detail about actor tags, when we get into creating some games later in the book. If you double-click on the Initial Scene, you will be taken to the level editor. Before we do that, let's go through the buttons shown in the following screenshot: The descriptions of the buttons in the previous screenshot are as as follows: Seems pretty easy, right? It is! GameSalad's user interface is simple. Even if you don't know what a certain button does, just hover your mouse over the button and a tooltip appears and tells you what the button does. Even though it's a very simple user interface, it is very powerful. Take for example, something as simple as the Enable Resolution Independence option. Simply selecting this takes out a lot of time from having to create two sets of images, a high resolution retina-friendly image, and a lower quality set for non-retina display images. With this option, all you have to do is create a high resolution set. Choose this option and GameSalad automatically creates a lower quality set of images for non-retina devices. How great is that? Such a simple option and yet it saves so much time and effort, and isn't simplicity what everyone wants? Now let's get into the scene editor Double-click our initial scene and you will see the Scene Editor, yes it may be a little daunting, but once you get used to the user interface, it is really quite simple. Let's break down all the buttons and see what they do: What do all these buttons mean? Following is a description of all the buttons and boxes: There we go! The GameSalad interface really is that easy to navigate! In this article, you set up an account with GameSalad, you downloaded and installed it and now you know how to use the interface. GameSalad has such a simple interface, but it is really powerful. As we looked at earlier, an option as simple as Resolution Independence is so easy to select and yet one click takes off so much time from creating different sets of images that can be used for developing. This is what makes GameSalad so great; it's such a simple user interface and yet it is so powerful. What is so amazing about all of it, is that there's no programming involved whatsoever! For those who don't have the smartness to program a full game, this is what everyone else wants, simple, quick, and super powerful.
Read more
  • 0
  • 0
  • 5212

article-image-unreal-development-toolkit-level-design-hq
Packt
23 Nov 2011
5 min read
Save for later

Unreal Development Toolkit: Level Design HQ

Packt
23 Nov 2011
5 min read
(For more resources related to this subject, see here.) So let's get on with it. We will first look at downloading the UDK, and install it on your PC. Time for action – UDK download and installation Download the latest version of UDK. Log on to www.udk.com and download the latest version of unreal development kit beta. Once you download the UDK Installer, go ahead and install the UDK. The default directory for installing UDK is C:UDKUDK-VersionRelease. Version Release will be the month and year that the UDK you downloaded was built. UDK folder structure The UDK folder structure looks like the following screenshot: The UDK folder structure consists of the following four folders: Binaries: game/binary executable. Development: source code for UDK. Engine: engine files. UTGame: game files. For level-design and environment creation, the important folder here is the content folder. The packaged environment's assets such as models, textures, materials, sounds, and such are stored here. For environment creation and level design, the most important folder is UTGame | Content | Environments. It contains all the files you need to create your map, as shown in the following screenshot: UDK extension is the UDK package's name. This is how the models and textures are stored in UDK. Think of UDK extension as folders. Inside those folders are stored all the models, animations, textures, materials, and similar assets. You can browse the UDK files through the UDK editor.   UDK is the map file extension.   Time for action – launching the editor To launch the unreal editor, go to the Start Menu | Unreal Development Kit | UDK Version | Editor. Another way to launch the editor is to create a shortcut. To do this, go to the installation folder: UDKUDK-VersionReleaseBinaries, locate UDKLift.exe, right-click and select Send To | Desktop (create shortcut), as shown in the following screenshot: Once on you have created the shortcut on your desktop, right-click the shortcut and select Properties. Then, in the Target box under the Shortcut tab, add editor at the end of the text. It should look something like the following screenshot: Now double-click on the desktop icon and launch the UDK Editor. Autosave When you first launch the editor, you will have Autosave automatically enabled. This will save your map at a chosen timed interval. You can set how often it will automatically save by clicking the Left Mouse Button (LMB) on the arrow on the bottom-right of the Autosave Interval and choosing the time you want, as shown in the following screenshot: You will find the Autosave feature at the bottom right of the editor. If you enable Autosave, there are a few options such as Interval and Type. Save manually by going up to File | Save As. Content browser Content browser is where you will find off the game's assets. Placing static meshes (models), textures, sounds, and game entities such as player starts, weapons, and so on, can all be done through the content browser. You will be using the content browser very often. To open the content browser click on the top menu bar, as shown in the following screenshot: Packages are where you will find specific items contained within the UDK. Things such as static meshes are contained within a package. You can search for a package, or just find the package you want to use and select it as shown in the following screenshot: The top of the content browser contains a search box as well as a filter box. This is very useful. You can sort out the content in the browser by animation sets, material instances, static meshes, sounds, and so on. This helps a lot when looking for items. The next screenshot lists full names of the items within a selected package. You can sort by clicking on the Name, Type, Tags, or Path fields, and it will re-arrange the content's preview: The content browser is one of the most commonly used tools in UDK. Get comfortable using the content browser. Spend some time navigating around it. UDK basics covers the most essential tools and functions you need to know to get started with UDK. You'll be able to quickly jump into UDK and begin feeling comfortable using the most commonly used functions. What just happened? So we know how to launch the editor, how to use the Autosave function, and where to find the content browser. We are now going to look at how to move and rotate around the editor. Time for action – movement and rotation Time to have a look at movement, rotation, and navigating around the editor. Navigation Buttons used to navigate around UDK. UDK These are your primary keys for navigating and rotating using the editor: Left Mouse Button (LMB): pan right/left/forward/backward movements Right Mouse Button (RMB): rotate, look around LMB+RMB: up/down WASD key navigation The following are other forms of primary keys for navigating and rotating around the editor: Click and hold RMB. As you hold it, use the WASD keyboard keys to move around as you would in a first person shooter game. WASD movement is great if you are familiar with hammer source mapping. MAYA users If you are familiar with Maya, the following will be your primary keys for navigating and rotating around the editor. Hold down the U key U+ LMB: rotate, look around U+ RMB: forward/backward movements U+ MMB: right/left/up/down movements What just happened? Now that you have installed UDK and know what the content browser is, you are ready to begin. So let's get started.
Read more
  • 0
  • 0
  • 2010

article-image-irrlicht-creating-basic-template-application
Packt
21 Nov 2011
3 min read
Save for later

Irrlicht: Creating a Basic Template Application

Packt
21 Nov 2011
3 min read
(For more resources related to this topic, see here.) Creating a new empty project Let's get started by creating a new project from scratch. Follow the steps that are given for the IDE and operating system of your choice. Visual Studio Open Visual Studio and select File | New | Project from the menu. Expand the Visual C++ item and select Win32 Console Application. Click on OK to continue: In the project wizard click on Next to edit the Application Settings. Make sure Empty project is checked. Whether Windows application or Console application is selected will not matter. Click on Finish and your new project will be created: Let's add a main source file to the project. Right-click on Source Files and select Add New Item...|. Choose C++ File(.cpp) and call the file main.cpp: CodeBlocks Use the CodeBlocks project wizard to create a new project as described in the last chapter. Now double-click on main.cpp to open this file and delete its contents. Your main source file should now be blank. Linux and the command line Copy the make file of one of the examples from the Irrlicht examples folder to where you wish to create your new project. Open the make file with a text editor of your choice and change, in line 6, the target name to what you wish your project to be called. Additionally, change, in line 10, the variable IrrlichtHome to where you extracted your Irrlicht folder. Now create a new empty file called main.cpp. Xcode Open Xcode and select File | New Project. Select Command Line Tool from Application. Make sure the type of the application is set to C++ stdc++: When your new project is created, change Active Architecture to i386 if you are using an Intel Mac, or ppc if you are using a PowerPC Mac. Create a new target by right-clicking on Targets, select Application and click on Next. Target Name represents the name of the compiled executable and application bundle: The target info window will show up. Fill in the location of the include folder of your extracted Irrlicht package in the field Header Search Path and make sure the field GCC_ PREFIX_HEADER is empty: Right-click on the project file and add the following frameworks by selecting Add Existing Frameworks...|: Cocoa.framework Carbon.framework IOKit.framework OpenGL.framework Now, we have to add the static library named libIrrlicht.a that we compiled in Chapter 1, Installing Irrlicht. Right-click on the project file and click on Add | Existing Frameworks.... Now click on the button Add Other... and select the static library. Delete the original compile target and delete the contents of main.cpp. Time for action – creating the main entry point Now that our main file is completely empty, we need a main entry point. We don't need any command-line parameters, so just go ahead and add an empty main() method as follows: int main(){ return 0;} If you are using Visual Studio, you need to link against the Irrlicht library. You can link from code by adding the following line of code: #pragma comment(lib, "Irrlicht.lib") This line should be placed between your include statements and your main() function. If you are planning to use the same codebase for compiling on different platforms, you should use a compiler-specific define statement, so that this line will only be active when compiling the application with Visual Studio. #if defined(_MSC_VER) #pragma comment(lib, "Irrlicht.lib")#endif
Read more
  • 0
  • 0
  • 1666
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 $19.99/month. Cancel anytime
article-image-unity-3-building-rocket-launcher
Packt
07 Sep 2011
8 min read
Save for later

Unity 3: Building a Rocket Launcher

Packt
07 Sep 2011
8 min read
  (For more resources on this subject, see here.) Mission briefing We will create a character that carries a rocket launcher and is able to shoot it as well as creating the camera view looking back from the character shoulder (third-person camera view). Then, we will add the character controller script to control our character, and the player will have to hold the Aim button to be able to shoot the rocket, similar to the Resident Evil 4 or 5 styles. What does it do? We will start with applying the built-in CharacterMotor, FPSInputController, and MouseLook scripts from the built-in FPS character controller. Then, we will add the character model and start creating a new script by adapting part of the code in the FPSInputController script. Then, we will be able to control the animation for our character to shoot, walk, run, and remain idle. Next, we will create a rocket prefab and the rocket launcher script to fire our rocket. We will use and adapt the built-in explosion and fire trial particle in Unity, and attach them to our rocket prefab. We will also create a new smoke particle, which will appear from the barrel of the rocket launcher when the player clicks Shoot. Then, we will create the scope target for aiming. We will also create the launcher and smoke GameObject, which are the start position of the rocket and the smoke particle. Finally, we will add the rocket GUITexture object and script to track the number of bullets we have let, at player each shot. We will also add the Reload but on to refill our bullet when the character is out of the bullet. Why Is It Awesome? When we complete this article, we will be able to create the third-person shooter style camera view and controller, which is very popular in many games today. We will also be able to create a rocket launcher weapon and particle by using the prefab technique. Finally, we will be able to create an outline text with the GUITexture object for tracking the number of bullets left. Your Hotshot Objectives In this article, we will use a third-person controller script to control our character and combine it with the built-in first-person controller prefab style to create our third-person shooter script to fire a rocket from the rocket launcher. Here is what we will do: Setting up the character with the first-person controller prefab Creating the New3PSController and MouseLook_JS scripts Create a rocket launcher and a scope target Create the rockets and particles Create the rocket bullet UI Mission Checklist First, we need the chapter 5 project package, which will include the character model with a gun from the Unity FPS tutorial website, and all the necessary assets for this article. So, let's browse to http://www.packtpub.com/support?nid=8267 and download Chapter5.zip package. Unzip it and we will see Chapter5.unitypackage, and we are ready. Setting up the character with the first-person controller prefab In the first section of this article, we will make all the necessary settings before we create our character on the scene. We will set up the imported assets and make sure that all the assets are imported in the proper way and are ready to use by using the Import Package in the Project view inside Unity. Then, we will set the light, level, camera, and put our character in the scene with the first-person controller prefab. We will import the Chapter5.unitypackage package to Unity, which contains the Chapter5 folder. Inside this folder, we will see five subfolders, which are Fonts, Level, Robot Artwork, Rocket, and UI. The Fonts folder will contain the Font file, which will be used by the GUI. The Level folder will contain the simple level prefab, its textures, and materials. Robot Artwork is the folder that includes the character FBX model, materials, and textures, which can be taken from the Unity FPS tutorial. The Rocket folder contains the rocket and rocket launcher FBX models, materials, and textures, which can be taken from the Unity FPS tutorial. Finally, the UI folder includes all the images, which we will use to create the GUI. Prepare for Lift Off In this section, we will begin by importing the chapter 5 Unity package, checking all the assets, setting up the level, and adding the character to the scene with the FPS controller script. First, let's create a new project and name it RocketLauncher, and this time we will include the built-in Character Controller package and Particles package by checking the Character Controller.unityPackage and Particles.unityPackage checkboxes in the Project Wizard. Then, we will click on the Create Project but on, as shown in the following screenshot: Next, import the assets package by going to Assets | Import Package | Custom Package.... Choose Chapter5.unityPackage, which we just downloaded, and then click on the Import but on in the pop-up window link, as shown in the following screenshot: Wait until it's done, and you will see the Chapter5 folder in the Window view. Make sure that we have all have folders, which are Fonts, Level, Robot Artwork, Rocket, and UI, inside this folder. Now, let's create something. Engage Thrusters In this section, we will set up the scene, camera view, and place our character in the scene: First, let's begin with creating the directional light by going to GameObject | Create Other | Directional Light, and go to its Inspector view to set the rotation X to 30 and the position (X: 0, Y: 0, Z: 0). Then, add the level to our scene by clicking on the Chapter5 folder in the Project view. In the Level folder, you will see the Level Prefab; drag it to the Hierarchy view and you will see the level in our scene. Next, remove the Main Camera from the Hierarchy view because we will use the camera from the built-in First Person Controller prefab. So, right-click on the Main Camera on the Hierarchy view and choose Delete to remove it. Then, add the built-in First Person Controller prefab to the Hierarchy view by going to the Standard Assets folder. Under the Character Controllers folder, you will see the First Person Controller prefab; drag it to the Hierarchy view. In the Hierarchy view, click on the arrow in the front of the First Person Controller object to see its hierarchy, similar to the one shown in the following screenshot: Then, we go back to the Project view. In the Chapter5 folder inside Robot Artwork, drag the robot.fbx object (as shown in the following screenshot) on top of the Main Camera inside the First Person Controller object in the Hierarchy. This will cause the editor to show the window that tells us this action will break the prefab, so we just click on the Continue but on to break it. It means that this game object will not be linked to the original prefab. Next, remove the Graphics object above the Main Camera. Right-click on it and choose Delete. Now we will see something similar to the following screenshot: We have put the robot object as a child of the camera because we want our character to rotate with the camera. This will make our character always appear in front of the camera view, which is similar to the third-person view. This setup is different from the original FPS prefab because in the first person view, we will not see the character in the camera view, so there is no point in calculating the rotation of the character Now, click on the First Person Controller object in the Hierarchy view to bring up the Inspector view, and set up the Transform Position of X: 0, Y: 1.16, Z: 0|. Then, go to the Character Controller, and set all values as follows: Character Controller (Script) Height: 2.25 Center X: -0.8, Y: 0.75, Z: 1.4 Move down one step by clicking on Main Camera in the Hierarchy view and go to its Inspector view to set the value of Transform and Mouse Look as follows: Transform Position X: 0, Y: 1.6, Z: 0 Mouse Look (Script) Sensitivity Y: 5 Minimum Y: -15 We will leave all the other parameters as default and use the default values. Then, we will go down one more step to set the Transform of the robot by clicking on it to bring up its Inspector view, and set the following: Now, we are done with this step. In the next step, we will adjust and add some code to control the animation and movement of our character the FPSInputController script. If the user presses it, we want the character to stop moving and play the shooting animation to prepare the character to be able to fire. We also set the maximum and minimum of the camera rotation on the Y-axis, which limits the camera to rotate up and down only. Then, we set the motor.inputMoveDirection to Vector3. zero because we don't want our character to move while he/she is executing the shooting action. On the other hand, if the user doesn't press E, we check for the user input. If the user presses the right arrow or let arrow, we change the speed to run speed; if not we set it to walk speed. Then, we applied the movement speed to motor. movement.maxForwardSpeed, motor.movement.maxSidewaysSpeed, and motor.movement.maxBackwardsSpeed.
Read more
  • 0
  • 0
  • 3982

article-image-cryengine-3-fun-physics
Packt
12 Jul 2011
4 min read
Save for later

CryENGINE 3: Fun Physics

Packt
12 Jul 2011
4 min read
CryENGINE 3 Cookbook Over 90 recipes written by Crytek developers for creating third-generation real-time games Low gravity In this simple recipe, we will look at utilizing the GravityBox to set up a low gravity area within a level. Getting ready Have Sandbox open Then open My_Level.cry How to do it... To start, first we must place down a GravityBox. In the RollupBar, click on the Entities button. Under the Physics section, select GravityBox. Place the GravityBox on the ground: Keeping the default dimensions (20, 20, 20 meters), the only property here that we want to change is the gravity. The default settings in this box set this entire area within the level to be a zero gravity zone. To adjust the up/down gravity of this, we need to change the value of gravity and the Z axis. To mimic normal gravity, this value would need to be set to the acceleration value of -9.81. To change this value to a lower gravity value, (something like the Moon's gravity) simply change it to a higher negative value such as -1.62. How it works... The GravityBox is a simple bounding box which overrides the defined gravity in the code (-9.81) and sets its own gravity value within the bounding box. Anything physicalized and activated to receive physics updates will behave within the confines of these gravitational rules unless they fall outside of the bounding box. There's more... Here are some useful tips about the gravity objects. Uniform property The uniform property within the GravityBox defines whether the GravityBox should use its own local orientation or the world's. If true, the GravityBox will use its own local rotation for the gravitational direction. If false, it will use the world's direction. This is used when you wish to have the gravity directed sideways. Set this value to True and then rotate the GravityBox onto its side. Gravity sphere Much like the GravityBox, the GravitySphere holds all the same principles but in a radius instead of a bounding box. The only other difference with the GravitySphere is that a false uniform Boolean will cause any object within the sphere to be attracted/repulsed from the center of the axis.   Hangman on a rope In this recipe, we will look at how we can utilize a rope to hang a dead body from it. Getting ready Open Sandbox Then open My_Level.cry How to do it... Begin by drawing out a rope: Open the RollupBar. From the Misc button, select Rope. With Grid Snap on and set to 1 meter, draw out a straight rope that has increments of one meter (by clicking once for every increment) up to four meters (double-click to finalize the rope). Align the rope so that from end to end it is along the Z axis (up and down) and a few meters off the ground: Next, we will need something solid to hang the rope from. Place down a solid with 1, 1, 1 meter. Align the rope underneath the solid cube while keeping both off the ground. Make sure when aligning the rope to get the end constraint to turn from red to green. This means it is attached to a physical surface: Lastly, we will need to hang a body from this rope. However, we will not hang him in the traditional manner, but rather by one of his feet. In the RollupBar, click on the Entities button. Under the Physics section, select DeadBody. Rotate this body up-side-down and align one of his feet to the bottom end of the rope. Select the rope to make sure the bottom constraint turns green to signal that it is attached. Verify that the Hangman on a rope recipe works by going into game mode and punching the dead body: How it works... The rope is a complicated cylinder that can contain as many bending segments as defined and is allowed to stretch and compress depending on the values defined. Tension and breaking strength can also be defined. But since ropes have expensive physics properties involved, they should be used sparingly.  
Read more
  • 0
  • 0
  • 2087

article-image-blender-25-modeling-basic-humanoid-character
Packt
01 Jul 2011
14 min read
Save for later

Blender 2.5: modeling a basic humanoid character

Packt
01 Jul 2011
14 min read
Mission Briefing Our objective is to create a basic model of a humanoid, with all the major parts included and correctly shaped: head, arms, torso, legs, and feet will be defined. We won't be creating fine details of the model, but we will definitely pay attention to the process and the mindset necessary to achieve our goal. What Does It Do? We'll start by creating a very simple (and ugly) base mesh that we can tweak later to get a nice finished model. From a single cube, we will be creating an entire model of a basic humanoid character, and take the opportunity to follow our own "feelings" to create the finished model. Why Is It Awesome? This project will help you learn some good points that will be handy when working on future projects (even in complex projects). First of all, we'll learn a basic procedure for applying the box modeling technique to create a base mesh. We'll then learn that our models don't have to look nice all the time to ensure a proper result, instead we must have a proper understanding of where we are heading to avoid getting lost along the way. Finally, we'll learn to separate the complexity of a modeling task into two different parts, using the best tools for the job each time (thus having a more enjoyable time and very good freedom to creative). The brighter side of this project will be working with the sculpting tools, since they give us a very cool way of tweaking meshes without having to handle individual vertices, edges, or faces. This advantage constitutes an added value for our workflow: we can separate the boring technical parts of modeling (mostly extruding and defining topology) from the actual fine tweaking of the form. Moreover, if we have the possibility of using the sculpt tools with a pen tablet, the modeling experience will be greatly improved and will feel extremely intuitive. Your Hotshot Objectives Although this project is not really complex, we will separate it into seven tasks, to make it easier to follow. They are: Creating the base mesh Head Arms Torso Legs Feet and final tweaks Scene setup Creating the Base Mesh Let's begin our project by creating the mesh that will be further tweaked to get our final model. For this project we'll apply a methodology (avoiding overly complicated, unintelligible, written descriptions) that will give us some freedom and allow us to explore our creativity without the rigidity of having a strict blueprint to follow. There's a warning, though: our model will look ugly most of the time. This is because in the initial building process we're not going to put so much emphasis on how it looks but on the structure of the mesh. Having said that, let's start with the first task of the project. Prepare for Lift Off Fire up Blender, delete the default lamp, set the name of the default cube to character(from the Item panel, Properties sidebar) and save the file as character.blend in the project's directory. Engage Thrusters First, we need to set the character object with a Mirror modifier, so that we only need to work on one side of the character while the other side gets created automatically as we work. Select the character object, switch to Edit Mode and then switch to Front View (View | Front), then add a new edge loop running vertically by using the Loop Cut and Slide tool. Make sure that the new edge loop is not moved from the center of the cube, so that it separates the cube into two mirrored sides. Now set the viewport shading to wireframe (press the Z key), select the vertices on the left-hand side of the cube, and delete them (press the X key). Now let's switch back to Object Mode, then go to the Modifiers tab in the Properties Editor and add a new Mirror Modifier to the character object. On the settings panel for the Mirror Modifier, let's enable the Clipping option. This will leave us with the object set up according to our needs. Switch to Edit Mode for the character object and then to Face Select mode. Select the upper face of the mesh, extrude it (E key) and then move the extrusion 1 unit upwards, along the Z axis. Now perform a second extrusion, this time on the face that remains selected from the previous one, and move it 1 unit upwards too; this will leave us with three sections (the lowest one is the biggest). Follow along by switching to Right View (View | Right), extrude again, press Escape, and then move the extrusion 0.2 units upwards (press the G key, Z key, then type 0.2). With the upper face selected, let's scale it down by a factor of 0.3 (S key, then type 0.3) and then move it by 0.6 units along the Y axis (G key, Y key, then type 0.6). Continue by extruding again and moving the extrusion 0.5 units upwards (G key, Z key, then type 0.5). Then add another extrusion, moving it up by 0.1 units (G key, Z key, then type 0.1). With the last extrusion selected, perform a scale operation, by a factor of 1.5 (S key, then type 1.5). Right after that, extrude again and move the extrusion 1.5 units upwards (G key, Z key, then type 1.5). Now let's rotate the view freely, so that the face of the last extrusion that faces the front is selectable, select it and move it -0.5 units along the Y axis (press the G key, Y key, then type -0.5).Let's take a look at a screenshot to make sure that we are on the right path: Note the (fairly noticeable) shapes showing the neck area, the head, and the torso of our model. Take a look at the face on the model's side from where we'll later extrude the arm. Now let's switch to Front View (View | Front), then select the upper face on the side of the torso of the model, extrude it, press Escape, and move it 0.16 units along the X axis (G key, X key, then type 0.16). Continue by scaling it down by a factor of 0.75 (S key, then type 0.75) and move it up by 0.07 units (press the G key, Z key, then type 0.07). Then switch to Right View (View | Right) and move it 0.2 units along the Y axis (press the G key, Y key, then type 0.2). This will give us the starting point to extrude the arm. Switch to Front View (View | Front) and perform another extrusion (having selected the face that remains selected by the previous extrusion), press Escape, and then move it 0.45 units along the X axis (press the G key, X key, then type 0.45). Then let's switch to Edge Select Mode, deselect all the edges that could be selected (Select | Select/Deselect All), rotate the view to be able to select any of the horizontal edges of the last extrusion, and then select the upper horizontal edge of the last extrusion; then move it -0.16 units along the X axis (G key, X key, then type -0.16). Right after that, let's select the lower horizontal edge of the last extrusion and move it 0.66 units upwards (G key, Z key, then type 0.66). Finalize this tweak by selecting the last two edges that we worked with and move them -0.15 units along the X axis (press the G key, X key, then type -0.15). Let's also select the lower edge of the first extrusion that we made for the arm and move it 0.14 units along the X axis (press the G key, X key, then type 0.14). Since this process is a bit tricky, let's use a screenshot, to help us ensure that we are performing it correctly: The only reason to perform this weird tweaking of the base mesh is to ensure a proper topology (internal mesh structure) for the shoulder when the model is finished. Let's remember to take a look at the shoulder of the finished model and compare it with the previous screenshot to understand it. Make sure to only select the face shown selected in the previous screenshot and switch back to Front View (View | Front) to work on the arms. Extrude the selected face, press Escape, and then move it by 1.6 units along the X axis (press the G key, X key, then type 1.6). Then scale it down by a factor of 0.75 (press the S key, then type 0.75) and move it up 0.07 units (press the G key, Z key, then type 0.07). Continue by performing a second extrusion, press Escape and then move it 1.9 units along the X axis (press the G key, X key, then type 1.9). Then let's perform a scale constrained to the Y axis, this time by a factor of 0.5 (press the S key, Y key, then type 0.5). To perform some tweaks, let's switch to Top View (View | Top) and move the selected face 0.17 units along the Y axis (press the G key, Y key, then type 0.17). To model the simple shape that we will create for the hand, let's make sure that we have selected the rightmost face from the last extrusion, extrude it, and move it 0.25 units along the X axis (press the G key, X key, then type 0.25). Then perform a second extrusion and move it 0.25 units along the X axis as well, and finish the extrusions by adding a last one, this time moving it 0.6 units along the X axis (press the G key, X key, then type 0.6). For the thumb, let's select the face pointing forwards in the second-last extrusion, extrude it, and move the extruded face to the right and down (remember we are in Top View) so that it looks well shaped with the rest of the hand. For this we can perform a rotation of the selected face to orient it better. To finish the hand, let's select the faces forming the thumb and the one between the thumb and the other "fingers", and move them -0.12 units along the Y axis (press the G key, Y key, then type -0.12). Also select the two faces on the other side of the face and move them 0.08 units along the Y axis (press the G key, Y key, then type 0.08). The following screenshot should be very helpful to follow the process: Now it's time to model the legs of our character. For that, let's pan the 3D View to get the lower face visible, select it, extrude it, and move it -0.4 units (press the G key, Z key, then type -0.4). Now switch to Edge Select Mode, select the rightmost edge of the face we just extruded down, and move it -0.85 units along the X axis (G key, X key, then type -0.85). To extrude the thigh, let's first switch to Face Select Mode, select the face that runs diagonally after we moved the edge in the previous step, then switch to Front View (View | Front), extrude the face, press Escape, and then apply a scale operation along the Z axis by a factor of 0 (press the S key, Z key, then type 0), to get it looking entirely flat. With the face from the last extrusion selected, let's move it -0.8 units along the Z axis (press the G key, Z key, then type -0.8). Right after that, let's scale the selected face by a factor of 1.28 along the X axis (press the S key, X key, then type 1.28) and move it 0.06 units along the X axis (press the G key, X key, then type 0.06). Now switch to Right View (View | Right), scale it by a factor of 0.8 (press the S key, Y key, then type 0.8), and then move it -0.12 units along the Y axis (press the G key, Y key, then type -0.12). Perform another extrusion, then press Escape and move it -2.2 units along the Z axis (press the G key, Z key, then type -2.2). To give it a better form, let's now scale the selected face by a factor of 0.8 along the Y axis (press the S key, Y key, then type 0.8) and move it 0.05 units along the Y axis (press the G key, Y key, then type 0.05). To complete the thigh, let's switch to Front View (View | Front), scale it by a factor of 0.7 along the X axis (press the S key, X key, then type 0.7), and then move it -0.18 units along the X axis (press the G key, X key, then type -0.18). Right after the thigh, let's continue working on the leg. Make sure that the face from the tip of the previous extrusion is selected, extrude it, press Escape, then move it -2.3 units along the Z axis (press the G key, Z key, then type -2.3). Then let's switch to Right View (View | Right), scale it by a factor of 0.7 along the Y axis (press the S key, Y key, then type 0.7), and move it -0.02 units along the Y axis (press the G key, Y key, then type -0.02). Now we just need to create the feet by extruding the face selected previously and moving it -0.6 units along the Z axis (press the G key, Z key, then type -0.6). Then select the face of the last extrusion that faces the front, extrude it, press Escape, and move it -1.9 units along the Y axis. As a final touch, let's switch to Edge Select mode, then select the upper horizontal edge of the last extrusion and move it -0.3 units along the Z axis (press the G key, Z key, then type -0.3). Let's take a look at a couple of screenshots showing us how our model should look by now: In the previous screenshot, we can see the front part, whereas the back side of the model is seen in the next one. Let's take a couple of minutes to inspect the screenshots and compare them to our actual model, to be entirely sure that we have the correct mesh now. Notice that our model isn't looking especially nice yet; that's because we've just worked on creating the mesh, the actual form will be worked in the coming tasks. Objective Complete - Mini Debriefing In this task we just performed the very initial step of our modeling process: creating the base mesh to work with. In order to avoid overly complicated written explanations we are using a modeling process that leaves the actual "shaping" for later, so we only worked out the topology of our mesh and laid out some simple foundations such as general proportions. The good thing about this approach is that we put in effort where it is really required, saving some time and enjoying the process a lot more. Classified Intel There are two main methods for modeling: poly-to-poly modeling and box modeling. The poly-to-poly method is about working with very localized (often detailed) geometry, paying attention to how each polygon is laid out in the model. The box modeling method is about constructing the general form very fast, by using the extrude operation, while paying attention to general aspects such as proportions, deferring the detailed tweaks for later. In this project we apply the box modeling method. We just worked out a very simple mesh, mostly by performing extrusions and very simple tweaks. Our main concern while doing this task was to keep proportions correct, forgetting about the fine details of the "form" that we are working out. The next tasks of this project will be about using Blender's sculpting tools to ease the tweaking job a lot, getting a very nice model in the end without having to tweak individual vertices!
Read more
  • 0
  • 0
  • 5160

article-image-how-create-new-vehicle-cryengine-3
Packt
23 Jun 2011
12 min read
Save for later

How to Create a New Vehicle in CryENGINE 3

Packt
23 Jun 2011
12 min read
  CryENGINE 3 Cookbook Over 100 recipes written by Crytek developers for creating AAA games using the technology that created Crysis 2 Creating a new car mesh (CGA) In this recipe, we will show you how to build the basic mesh structure for your car to be used in the next recipe. This recipe is not to viewed as a guide on how to model your own mesh, but rather as a template for how the mesh needs to be structured to work with the XML script of the vehicle. For this recipe, you will be using 3DSMax to create and export your .CGA. .CGA (Crytek Geometry Animation): The .cga file is created in the 3D application and contains animated hard body geometry data. It only supports directly-linked objects and does not support skeleton-based animation (bone animation) with weighted vertices. It works together with .anm files. Getting ready Create a box primitive and four cylinders within Max and then create a new dummy helper. How to do it... After creating the basic primitives within Max, we need to rename these objects. Rename the primitives to match the following naming convention: Helper = MyVehicle Box = body Front Left Wheel = wheel1 Front Right Wheel = wheel2 Rear Left Wheel = wheel3 Rear Right Wheel = wheel4 Remember that CryENGINE 3 assumes that y is forward. Rotate and reset any x-forms if necessary. From here you can now set up the hierarchy to match what we will build into the script: In Max, link all the wheels to the body mesh. Link the body mesh to the MyVehicle dummy helper. Your hierarchy should look like the following screenshot in the Max schematic view: Next, you will want to create a proxy mesh for each wheel and the body. Be sure to attach these proxies to each mesh. Proxy meshes can be a direct duplication of the simple primitive geometry we have created. Before we export this mesh, make one final adjustment to the positioning of the vehicle: Move the body and the wheels up on the Z axis to align the bottom surface of the wheels to be flushed with 0 on the Z. Without moving the body or the wheels, be sure that the MyVehicle helper is positioned at 0,0,0 (this is the origin of the vehicle). Also, re-align the pivot of the body to 0,0,0. Once complete, your left viewport should look something like the following screenshot (if you have your body still selected): After setting up the materials, you are now ready to export the CGA: Open the CryENGINE Exporter from the Utilities tab. Select the MyVehicle dummy helper and click the Add Selected button. Change the export to: Animated Geometry (*.cga). Set Export File per Node to True. Set Merge All Nodes to False. Save this Max scene in the following directory: MyGameFolderObjectsvehiclesMyVehicle. Now, click on Export Nodes to export the CGA. How it works... This setup of the CGA is a basic setup of the majority of the four wheeled vehicles used for CryENGINE 3. This same basic setup can also be seen in the HMMWV provided in the included assets with the SDK package of CryENGINE 3. Even though the complete HMMWV may seem to be a very complicated mesh used as a vehicle, it can also be broken down into the same basic structure as the vehicle we just created. The main reason for the separation of the parts on the vehicles is because each part performs its own function. Since the physics of the vehicle code drives the vehicle forward in the engine, it actually controls each wheel independently, so it can animate them based on what they can do at that moment. This means that you have the potential for a four wheel drive on all CryENGINE 3 vehicles, all animating at different speeds based on the friction that they grip. Since all of the wheels are parented to the body (or hull) mesh, this means that they drive their parent (the body of the vehicle) but the body also handles where the wheels need to be offset from in order to stay aligned when driving. The body itself acts as the base mesh for all other extras put onto the vehicle. Everything else from Turrets to Doors to Glass Windows branch out from the body. The dummy helper is only the parent for the body mesh due to the fact that it is easier to export multiple LODs for that vehicle (for example, HMMWV, HMMWV_LOD1, HMMWV_LOD2, and so on). In the XML, this dummy helper is ignored in the hierarchy and the body is treated as the parent node. There's more... Here are some of the more advanced techniques used. Dummy helpers for modification of the parts A more advanced trick is the use of dummy helpers set inside the hierarchy to be used in later reference through the vehicle's mod system. How this works is that if you had a vehicle such as the basic car shown previously, but you wanted to add on an additional mesh just to have a modified type of this same car (something like adding a spoiler to the back), then you can create a dummy helper and align it to the pivot of the object, so it will line up to the body of the mesh when added through the script later on. This same method was used in Crysis 2 with the Taxi signs on the top of the Taxi cars. The Taxi itself was the same model used as the basic civilian car, but had an additional dummy helper where the sign needed to be placed. This allowed for a clever way to save on memory when rendering multiple vehicle props within a single area but making each car look different. Parts for vehicles and their limitless possibilities Adding the basic body and four wheels to make a basic car model is only the beginning. There are limitless possibilities to what you can make as far as the parts on a vehicle are concerned. Anything from a classic gunner turret seen on the HMMWV or even tank turrets, all the way to arms for an articulated Battlemech as seen in the Crysis 2 Total Conversion mod—MechWarrior: Living Legends. Along with the modifications system, you have the capabilities to add on a great deal of extra parts to be detached and exploded off through the damage scripts later on. The possibilities are limitless. Creating a new car XML In this recipe, we will show you how to build a new script for CryENGINE 3 to recognize your car model as a vehicle entity. For this recipe, you must have some basic knowledge in XML formatting. Getting ready Open DefaultVehicle.xml in the XML editor of your choice (Notepad, Notepad++, UltraEdit, and so on). This XML will be used as the basic template to construct our new vehicle XML. DefaultVehicle.xml is found at the following location: MyGameFolderScriptsEntitiesVehiclesImplementationsXml. Open the MyVehicle.max scene made from the previous recipe to use as a reference for the parts section within this recipe. How to do it... Basic Properties: First, we will need to rename the filename to what the vehicle's name would be. Delete filename = Objects/Default.cgf. Rename name = DefaultVehicle to name = MyVehicle. Add actionMap = landvehicle to the end of the cell. Save the file as MyVehicle.XML. Your first line should now look like the following: Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you. <Vehicle name="MyVehicle" actionMap="landvehicle"> Now we need to add some physics simulation to the vehicle otherwise there might be some strange reactions with the vehicle. Insert the following after the third line (after the Buoyancy cell): <Simulation maxTimeStep="0.02" minEnergy="0.002" maxLoggedCollisions="2"/> Damages and Components: For now, we will skip the Damages and Components cells as we will address them in a different recipe. Parts: To associate the parts made in the Max file, the hierarchy of the geometry in 3DSMax needs to be the very same as is referenced in the XML. To do this, we will first clear out the class = Static cell and replace it with the following: <Part name="body" class="Animated" mass="100" component="Hull"> <Parts> </Parts> <Animated filename="objects/vehicles/MyVehicle/MyVehicle.cga" filenameDestroyed="objects/vehicles/HMMWV/HMMWV_damaged.cga"/> </Part> Now, within the <Parts> tag that is underneath the body, we will put in the wheels as the children: <Parts> <Part name="wheel1" class="SubPartWheel" component="wheel_1" mass="80"> <SubPartWheel axle="0" density="0" damping="-0.7" driving="1" lenMax="0.4" maxFriction="1" minFriction="1" slipFrictionMod="0.3" stiffness="0" suspLength="0.25" rimRadius="0.3" torqueScale="1.1"/> </Part> </Parts> Remaining within the <Parts> tag, add in wheels 2-4 using the same values as previously listed. The only difference is you must change the axle property of wheels 3 and 4 to the value of 1 (vehicle physics has an easier time calculating what the wheels need to if only two wheels are associated with a single axle). The last part that needs to be added in is the Massbox. This part isn't actually a mesh that was made in 3DSMax, but a generated bounding box, generated by code with the mass and size defined here in the XML. Write the following code snippet after the <body> tag: <Part name="massBox" class="MassBox" mass="1500" position="0,0,1." disablePhysics="0" disableCollision="0" isHidden="0"> <MassBox size="1.25,2,1" drivingOffset="-0.7"/> </Part> If scripted correctly, your script should look similar to the following for all of the parts on your vehicle: <Parts> <Part name="body" class="Animated" mass="100" component="Hull"> <Parts> <Part name="wheel1" class="SubPartWheel" component="wheel_1" mass="80"> <SubPartWheel axle="0" density="0" damping="-0.7" driving="1" lenMax="0.4" maxFriction="1" minFriction="1" slipFrictionMod="0.3" stiffness="0" suspLength="0.25" rimRadius="0.3" torqueScale="1.1"/> </Part> <Part name="wheel2" class="SubPartWheel" component="wheel_2" mass="80"> <SubPartWheel axle="0" density="0" damping="-0.7" driving="1" lenMax="0.4" maxFriction="1" minFriction="1" slipFrictionMod="0.3" stiffness="0" suspLength="0.25" rimRadius="0.3" torqueScale="1.1"/> </Part> <Part name="wheel3" class="SubPartWheel" component="wheel_3" mass="80"> <SubPartWheel axle="1" density="0" damping="-0.7" driving="1" lenMax="0.4" maxFriction="1" minFriction="1" slipFrictionMod="0.3" stiffness="0" suspLength="0.25" rimRadius="0.3" torqueScale="1.1"/> </Part> <Part name="wheel4" class="SubPartWheel" component="wheel_4" mass="80"> <SubPartWheel axle="1" density="0" damping="-0.7" driving="1" lenMax="0.4" maxFriction="1" minFriction="1" slipFrictionMod="0.3" stiffness="0" suspLength="0.25" rimRadius="0.3" torqueScale="1.1"/> </Part> </Parts> <Animated filename="objects/vehicles/MyVehicle/MyVehicle.cga" filenameDestroyed="objects/vehicles/HMMWV/HMMWV_damaged.cga"/> </Part> <Part name="massBox" class="MassBox" mass="1500" position="0,0,1." disablePhysics="0" disableCollision="0" isHidden="0"> <MassBox size="1.25,2,1" drivingOffset="-0.7"/> </Part> </Parts> Movement Parameters: Finally, you will need to implement the MovementParams needed, so that the XML can access a particular movement behavior from the code that will propel your vehicle. To get started right away, we have provided an example of the ArcadeWheeled parameters, which we can copy over to MyVehicle: <MovementParams> <ArcadeWheeled> <Steering steerSpeed="45" steerSpeedMin="80" steerSpeedScale="1" steerSpeedScaleMin="1" kvSteerMax="26" v0SteerMax="40" steerRelaxation="130" vMaxSteerMax="12"/> <Handling> <RPM rpmRelaxSpeed="2" rpmInterpSpeed="4" rpmGearShiftSpeed="2"/> <Power acceleration="8" decceleration="0.1" topSpeed="32" reverseSpeed="5" pedalLimitMax="0.30000001"/> <WheelSpin grip1="5.75" grip2="6" gripRecoverSpeed="2" accelMultiplier1="1.2" accelMultiplier2="0.5"/> <HandBrake decceleration="15" deccelerationPowerLock="1" lockBack="1" lockFront="0" frontFrictionScale="1.1" backFrictionScale="0.1" angCorrectionScale="5" latCorrectionScale="1" isBreakingOnIdle="1"/> <SpeedReduction reductionAmount="0" reductionRate="0.1"/> <Friction back="10" front="6" offset="-0.2"/> <Correction lateralSpring="2" angSpring="10"/> <Compression frictionBoost="0" frictionBoostHandBrake="4"/> </Handling> <WheeledLegacy damping="0.11" engineIdleRPM="500" engineMaxRPM="5000" engineMinRPM="100" stabilizer="0.5" maxTimeStep="0.02" minEnergy="0.012" suspDampingMin="0" suspDampingMax="0" suspDampingMaxSpeed="3"/> <AirDamp dampAngle="0.001,0.001,0.001" dampAngVel="0.001,1,0"/> <Eject maxTippingAngle="110" timer="0.3 "/> <SoundParams engineSoundPosition="engineSmokeOut" runSoundDelay="0" roadBumpMinSusp="10" roadBumpMinSpeed="6" roadBumpIntensity="0.3" maxSlipSpeed="11"/> </ArcadeWheeled> </MovementParams> After saving your XML, open the Sandbox Editor and place down from the Entities types: VehiclesMyVehicle. You should now be able to enter this vehicle (get close to it and press the F key) and drive around (W = accelerate, S = brake/reverse, A = turn left, D = turn right)! How it works... The parts defined here in the XML are usually an exact match to the Max scene that the vehicle is created in. As long as the naming of the parts and the name of the subobjects within Max are the same, the vehicle structure should work. The parts in the XML can themselves be broken down into their own properties: Name: The name of the part. Class: The classification of the part. Base (obsolete) Static: Static vehicle (should not be used). Animated: The main part for an active rigid body of a vehicle. AnimatedJoint: Used for any other part that's used as a child of the animated part. EntityAttachment (obsolete) Light: Light parts for headlights, rear light, and so on. SubPart (obsolete) SubPartWheel: Wheels. Tread: Used with tanks. MassBox: Driving Massbox of the vehicle. Mass: Mass of the part (usually used when the part is detached) Component: Which component this part is linked to. If the component uses useBoundsFromParts="1", then this part will also be included in the total bounding box size. Filename: If a dummy helper is created in Max to be used as a part, then an external mesh can be referenced and used as this part. DisablePhysics: Prevents the part from being physicalized as rigid. DisableCollision: Disables all collision. It is an useful example for mass blocks. isHidden: Hides the part from rendering. There's more... The def_vehicle.xml file found in MyGameFolderScriptsEntitiesVehicles, holds all the property's definitions that can be utilized in the XML of the vehicles. After following the recipes found in this article, you may want to review def_vehicle.xml for further more advanced properties that you can add to your vehicles.  
Read more
  • 0
  • 0
  • 4181
article-image-cryengine-3-terrain-sculpting
Packt
21 Jun 2011
11 min read
Save for later

CryENGINE 3: Terrain Sculpting

Packt
21 Jun 2011
11 min read
CryENGINE 3 Cookbook Over 100 recipes written by Crytek developers for creating AAA games using the technology that created Crysis 2 Creating a new level Before we can do anything with the gameplay of the project that you are creating, we first need a foundation of a new level for the player to stand on. This recipe will cover how to create a new level from scratch. Getting ready Before we begin, you must have Sandbox 3 open. How to do it... At any point, with Sandbox open, you may create a new level by following these steps: Click File (found in the top -left of the Sandbox's main toolbar). Click New. From here, you will see a new dialog screen that will prompt you for information on how you want to set up your level. The most important aspect of a level is naming it, as you will not be able to create a level without some sort of proper name for the level's directory and its .cry file. You may name your level anything you wish, but for the ease of instruction we shall refer to this level as My_Level: In the Level Name dialog box, type in My_Level. For the Terrain properties, use the following values: Use Custom Terrain Size: True Heightmap Resolution:512x512 Meters Per Unit: 1 Click OK. Depending on your system specifications, you may find that creating a new level will require anywhere from a few seconds to a couple of minutes. Once finished, the Viewport should display a clear blue sky with the dialog in your console reading the following three lines: Finished synchronous pre-cache of render meshes for 0 CGF's Finished pre-caching camera position (1024,1024,100) in 0.0 sec Spawn player for channel 1 This means that the new level was created successfully. How it works... Let's take a closer look at each of the options used while creating this new level. Using the Terrain option This option allows the developer to control whether to have any terrain on the level to be manipulated by a heightmap or not. Sometimes terrain can be expensive for levels and if any of your future levels contain only interiors or only placed objects for the player to navigate on, then setting this value to false will be a good choice for you and will save a tremendous amount of memory and aid in the performance of the level later on. Heightmap resolution This drop-down controls the resolution of the heightmap and the base size of the play area defined. The settings can range from the smallest resolution (128 x 128) all the way up to the largest supported resolution (8192 x 8192). Meters per unit If the Heightmap Resolution is looked at in terms of pixel size, then this dialog box can also be viewed as the Meters Per Pixel. This means that each pixel of the heightmap will be represented by these many meters. For example, if a heightmap's resolution has 4 Meters Per Unit (or Pixel), then each pixel on the generated heightmap will measure four meters in length and width on the level. Even though this Meters Per Unit can be used to increase the size of your level, it will decrease the fidelity of the heightmap. You will notice that attempting to smoothen out the terrain may be difficult as there will be a wider minimum triangle size set by this value. Terrain size This is the resulting size of the level with the equation of (Heightmap Resolution) x (Meters Per unit). Here are some examples of the results you will see (m = meters): (128x128) x 4m = 512x512m (512x512) x 16m = 8192x8192m (1024x1024) x 2m = 2048x2048m There's more... If you need to change your unit size after creating the map, you may change it by going into the Terrain Editor | Modify | Set Unit Size. This will allow you to change the original Meters Per Unit to the size you want it to be.   Generating a procedural terrain This recipe deals with the procedural generation of a terrain. Although never good enough for a final product because you will want to fine tune the heightmap to your specifications, these generated terrains are a great starting point for anyone new to creating levels or for anyone who needs to set up a test level with the Sandbox. Different heightmap seeds and a couple of tweaks to the height of the level and you can generate basic mountain ranges or islands quickly that are instantly ready to use. Getting ready Have My_Level open inside of Sandbox. How to do it... Up at the top-middle of the Sandbox main toolbar, you will find a menu selection called Terrain. From there you should see a list of options, but for now you will want to click on Edit Terrain. This opens the Terrain Editor window. The Terrain Editor window has a multitude of options that can be used to manipulate the heightmap in your level. But first we want to set up a basic generated heightmap for us to build a simple map with. Before we generate anything, we should first set the maximum height of the map to something more manageable. Follow these steps: Click Modify. Then click Set Max Height. Set your Max Terrain Height to 256 (these units are in meters). Now, we may be able to generate the terrain: Click Tools. Then click Generate Terrain. Modify the Variation (Random Base) to the value of 15. Click OK. After generating, you should be able to see a heightmap similar to the following screenshot: This is a good time to generate surface texture (File | Generate surface texture | OK), which allows you to see the heightmap with a basic texture in the Perspective View. How it works... The Maximum Height value is important as it governs the maximum height at which you can raise your terrain to. This does not mean that it is the maximum height of your level entirely, as you are still able to place objects well above this value. It is also important to note that if you import a grey scale heightmap into CryENGINE then this value will be used as the upper extreme of the heightmap (255,255,255 white) and the lower extreme will always be at 0 (0,0,0 black). Therefore the heightmap will be generated within 0 m height and the maximum height. Problems such as the following are a common occurrence: Tall spikes are everywhere on the map or there are massive mountains and steep slopes: Solution: Reduce the Maximum Height to a value that is more suited to the mountains and slopes you want The map is very flat and has no hills or anything from my heightmap: Solution: Increase the Maximum Height to a value that is suitable for making the hills you want There's more... Here are some other settings you might choose to use while generating the terrain. Terrain generation settings The following are the settings to generate a procedural terrain: Feature Size: This value handles the general height manipulations within the seed and the size of each mound within the seed. As the size of the feature depends greatly on rounded numbers it is easy to end up with a perfectly rounded island, therefore it is best to leave this value at 7.0. Bumpiness / Noise (Fade): Basically, this is a noise filter for the level. The greater the value, the more noise will appear on the heightmap. Detail (Passes): This value controls how detailed the slopes will become. By default, this value is very high to see the individual bumps on the slopes to give a better impression of a rougher surface. Reducing this value will decrease the amount of detail/roughness in the slopes seen. Variation: This controls the seed number used in the overall generation of the Terrain Heightmap. There are a total of 33 seeds ranging from 0 – 32 to choose from as a starting base for a basic heightmap. Blurring (Blur Passes): This is a Blur filter. The higher the amount, the smoother the slopes will be on your heightmap. Set Water Level: From the Terrain Editor window, you can adjust the water level from Modify | Set Water Level. This value changes the base height of the ocean level (in meters). Make Isle: This tool allows you to take the heightmap from your level and automatically lowers the border areas around the map to create an island. From the Terrain Editor window, select Modify | Make Isle.   Navigating a level with the Sandbox Camera The ability to intuitively navigate levels is a basic skill that all developers should be familiar with. Thankfully, this interface is quite intuitive to anyone who is already familiar with the WASD control scheme popular in most First Person Shooters Games developed on the PC. Getting ready You should have already opened a level from the CryENGINE 3 Software Development Kit content and seen a perspective viewport displaying the level. The window where you can see the level is called the Perspective Viewport window. It is used as the main window to view and navigate your level. This is where a large majority of your level will be created and common tasks such as object placement, terrain editing, and in-editor play testing will be performed. How to do it... The first step to interacting with the loaded level is to practice moving in the Perspective Viewport window. Sandbox is designed to be ergonomic for both left and right-handed users. In this example, we use the WASD control scheme, but the arrow keys are also supported for movement of the camera. Press W to move forwards. Then press S to move backwards. A is pressed to move or strafe left. Finally, D is pressed to move or strafe right. Now you have learned to move the camera on its main axes, it's time to adjust the rotation of the camera. When the viewport is the active window, hold down the right mouse button on your mouse and move the mouse pointer to turn the view. You can also hold down the middle mouse button and move the mouse pointer to pan the view. Roll the middle mouse button wheel to move the view forward or backward. Finally, you can hold down Shift to double the speed of the viewport movements. How it works... The Viewport allows for a huge diversity of views and layouts for you to view your level; the perspective view is just one of many. The perspective view is commonly used as it displays the output of the render engine. It also presents you a view of your level using the standard camera perspective, showing all level geometry, lighting, and effects. To experiment further with the viewport, note that it can also render subsystems and their toolsets such as flow graph, or character editor. There's more... You will likely want to adjust the movement speed and how to customize the viewport to your individual use. You can also split the viewport in multiple different views, which is discussed further. Viewport movement speed control The Speed input is used to increase or decrease the movement speed of all the movements you make in the main Perspective Viewport. The three buttons to the right of the Speed: inputs are quick links to the .1, 1, and 10 speeds. Under Views you can adjust the viewport to view different aspects of your level Top View, Front, and Left views will show their respective aspects of your level, consisting of bounding boxes and line-based helpers. It should be noted that geometry is not drawn. Map view shows an overhead map of your level with helper, terrain, and texture information pertaining to your level. Splitting the main viewport to several subviewports Individual users can customize the layout and set viewing options specific to their needs using the viewport menu accessed by right-clicking on the viewports header. The Layout Configuration window can be opened from the viewport header under Configure Layout. Once selected, you will be able to select one of the preset configurations to arrange the windows of the Sandbox editor into multiple viewport configurations. It should be recognized that in multiple viewport configurations some rendering effects may be disabled or performance may be reduced.  
Read more
  • 0
  • 0
  • 2212

article-image-cryengine-3-sandbox-basics
Packt
21 Jun 2011
9 min read
Save for later

CryENGINE 3: Sandbox Basics

Packt
21 Jun 2011
9 min read
  CryENGINE 3 Cookbook Over 100 recipes written by Crytek developers for creating AAA games using the technology that created Crysis 2 Placing the objects in the world Placing objects is a simple task; however, basic terrain snapping is not explained to most new developers. It is common to ask why, when dragging and dropping an object into the world, they cannot see the object. This section will teach you the easiest ways to place an object into your map by using the Follow Terrain method. Getting ready Have My_Level open inside of Sandbox (after completing either of the Terrain sculpting or Generating a procedural terrain recipes). Review the Navigating a level with the Sandbox Camera recipe to get familiar with the Perspective View. Have the Rollup Bar open and ready. Make sure you have the EditMode ToolBar open (right-click the top main ToolBar and tick EditMode ToolBar). How to do it... First select the Follow Terrain button. Then open the Objects tab within the Rollup Bar. Now from the Brushes browser, select any object you wish to place down (for example, defaults/box). You may either double-click the object, or drag-and-drop it onto the Perspective View. Move your mouse anywhere where there is visible terrain and then click once more to confirm the position you wish to place it in. How it works... The Follow Terrain tool is a simple tool that allows the pivot of the object to match the exact height of the terrain in that location. This is best seen on objects that have a pivot point close to or near the bottom of them. There's more... You can also follow terrain and snap to objects. This method is very similar to the Follow Terrain method, except that this also includes objects when placing or moving your selected object. This method does not work on non-physicalized objects.   Refining the object placement After placing the objects in the world with just the Follow Terrain or Snapping to Objects, you might find that you will need to adjust the position, rotation, or scale of the object. In this recipe, we will show you the basics of how you might be able to do so along with a few hotkey shortcuts to make this process a little faster. This works with any object that is placed in your level, from Entities to Solids. Getting ready Have My_Level open inside of Sandbox Review the Navigating a level with the Sandbox Camera recipe to get familiar with the Perspective View. Make sure you have the EditMode ToolBar open (right-click on the top main ToolBar and tick EditMode ToolBar). Place any object in the world. How to do it... In this recipe, we will call your object (the one whose location you wish to refine) Box for ease of reference. Select Box. After selecting Box, you should see a three axis widget on it, which represents each axis in 3D space. By default, these axes align to the world: Y = Forward X = Right Z = Up To move the Box in the world space and change its position, proceed with the following steps: Click on the Select and Move icon in the EditMode ToolBar (1 for the keyboard shortcut). Click on the X arrow and drag your mouse up and down relative to the arrow's direction. Releasing the mouse button will confirm the location change. You may move objects either on a single axis, or two at once by clicking and dragging on the plane that is adjacent to any two axes: X + Y, X + Z, or Y + Z. To rotate an object, do the following: Select Box (if you haven't done so already). Click on the Select and Rotate icon in the EditMode ToolBar (2 for the keyboard shortcut). Click on the Z arrow (it now has a sphere at the end of it) and drag your mouse from side to side to roll the object relative to the axis. Releasing the mouse button will confirm the rotation change. You cannot rotate an object along multiple axes. To scale an object, do the following: Select Box (if you haven't done so already). Click on the Select and Scale icon in the EditMode ToolBar (3 for the keyboard shortcut). Click on the CENTER box and drag your mouse up and down to scale on all three axes at once. Releasing the mouse button will confirm the scale change. It is possible to scale on just one axis or two axes; however, this is highly discouraged as Non-Uniform Scaling will result in broken physical meshes for that object. If you require an object to be scaled up, we recommend you only scale uniformly on all three axes! There's more... Here are some additional ways to manipulate objects within the world. Local position and rotation To make position or rotation refinement a bit easier, you might want to try changing how the widget will position or rotate your object by changing it to align itself relative to the object's pivot. To do this, there is a drop-down menu in the EditMode ToolBar that will have the option to select Local. This is called Local Direction. This setup might help to position your object after you have rotated it. Grid and angle snaps To aid in positioning of non-organic objects, such as buildings or roads, you may wish to turn on the Snap to Grid option. Turning this feature on will allow you to move the object on a grid (currently relative to its location). To change the grid spacing, click the drop-down arrow next to the number to change the spacing (grid spacing is in meters). Angle Snaps is found immediately to the right of the Grid Snaps. Turning this feature on will allow you to rotate an object by every five degrees. Ctrl + Shift + Click Even though it is a Hotkey, to many developers this hotkey is extremely handy for initial placement of objects. It allows you to move the object quickly to any point on any physical surface relative to your Perspective View.   Utilizing the layers for multiple developer collaboration A common question that is usually asked about the CryENGINE is how does one developer work on the same level as another at the same time. The answer is—Layers. In this recipe, we will show you how you may be able to utilize the layer system for not only your own organization, but to set up external layers for other developers to work on in parallel. Getting ready Have My_Level open inside of Sandbox. Review the Navigating a level with the Sandbox Camera to get familiar with the Perspective View. Have the Rollup Bar open and ready. Review the Placing the objects in the world (place at least two objects) recipe. How to do it... For this recipe, we will assume that you have your own repository for your project or some means to send your work to others in your team. First, start by placing down two objects on the map. For the sake of the recipe, we shall refer to them as Box1 and Box2. After you've placed both boxes, open the Rollup Bar and bring up the Layers tab. Create a new layer by clicking the New Layer button (paper with a + symbol). A New Layer dialog box will appear. Give it the following parameters: Name = ActionBubble_01 Visible = True External = True Frozen = False Export To Game = True Now select Box1 and open the Objects tab within the Rollup Bar. From here you will see in the main rollup of this object with values such as – Name, Helper Size, MTL, and Minimal Spec. But also in this rollup you will see a button for layers (it should be labelled as Main). Clicking on that button will show you a list of all other available layers. Clicking again on another layer that is not highlighted will move this object to that layer (do this now by clicking on ActionBubble_01). Now save your level by clicking—File | Save. Now in your build folder, go to the following location: -... GameLevelsMy_Level. From here you will notice a new folder called Layers. Inside that folder, you will see ActionBubble_01.lyr. This layer shall be the layer that your other developers will work on. In order for them to be able to do so, you must first commit My_Level.cry and the Layers folder to your repository (it is easiest to commit the entire folder). After doing so, you may now have your other developer make changes to that layer by moving Box1 to another location. Then have them save the map. Have them commit only the ActionBubble_01.lyr to the repository. Once you have retrieved it from the updated repository, you will notice that Box1 will have moved after you have re-opened My_Level.cry in the Editor with the latest layer. How it works... External layers are the key to this whole process. Once a .cry file has been saved to reference an external layer, it will access the data inside of those layers upon loading the level in Sandbox. It is good practice to assign a Map owner who will take care of the .cry file. As this is the master file, only one person should be in charge of maintaining it by creating new layers if necessary. There's more... Here is a list of limitations of what external layers cannot hold. External layer limitations Even though any entity/object you place in your level can be placed into external layers, it is important to note that there are some items that cannot be placed inside of these layers. Here is a list of the common items that are solely owned by the .cry file: Terrain Heightmap Unit Size Max Terrain Height Holes Textures Vegetation Environment Settings (unless forced through Game Logic) Ocean Height Time of Day Settings (unless forced through Game Logic) Baked AI Markup (The owner of the .cry file must regenerate AI if new markup is created on external layers) Minimap Markers  
Read more
  • 0
  • 0
  • 1534

article-image-working-away3d-cameras
Packt
06 Jun 2011
10 min read
Save for later

Working with Away3D Cameras

Packt
06 Jun 2011
10 min read
Away3D 3.6 Cookbook Over 80 practical recipes for creating stunning graphics and effects with the fascinating Away3D engine Cameras are an absolutely essential part of the 3D world of computer graphics. In fact, no real-time 3D engine can exist without having a camera object. Cameras are our eyes into the 3D world. Away3D has a decent set of cameras, which at the time of writing, consists of Camera3D, TargetCamera3D, HoverCamera3D, and SpringCam classes. Although they have similar base features, each one has some additional functionality to make it different. Creating an FPS controller There are different scenarios where you wish to get a control of the camera in first person, such as in FPS video games. Basically, we want to move and rotate our camera in any horizontal direction defined by the combination of x and y rotation of the user mouse and by keyboard keys input. In this recipe, you will learn how to develop such a class from scratch, which can then be useful in your consequential projects where FPS behavior is needed. Getting ready Set up a basic Away3D scene extending AwayTemplate and give it the name FPSDemo. Then, create one more class which should extend Sprite and give it the name FPSController. How to do it... FPSController class encapsulates all the functionalities of the FPS camera. It is going to receive the reference to the scene camera and apply FPS behavior "behind the curtain". FPSDemo class is a basic Away3D scene setup where we are going to test our FPSController: FPSController.as package utils { public class FPSController extends Sprite { private var _stg:Stage; private var _camera:Object3D private var _moveLeft_Boolean=false; private var _moveRight_Boolean=false; private var _moveForward_Boolean=false; private var _moveBack_Boolean=false; private var _controllerHeigh:Number; private var _camSpeed_Number=0; private static const CAM_ACCEL_Number=2; private var _camSideSpeed_Number=0; private static const CAM_SIDE_ACCEL_Number=2; private var _forwardLook_Vector3D=new Vector3D(); private var _sideLook_Vector3D=new Vector3D(); private var _camTarget_Vector3D=new Vector3D(); private var _oldPan_Number=0; private var _oldTilt_Number=0; private var _pan_Number=0; private var _tilt_Number=0; private var _oldMouseX_Number=0; private var _oldMouseY_Number=0; private var _canMove_Boolean=false; private var _gravity:Number; private var _jumpSpeed_Number=0; private var _jumpStep:Number; private var _defaultGrav:Number; private static const GRAVACCEL_Number=1.2; private static const MAX_JUMP_Number=100; private static const FRICTION_FACTOR_Number=0.75; private static const DEGStoRADs:Number = Math.PI / 180; public function FPSController(camera:Object3D,stg:Stage, height_Number=20,gravity:Number=5,jumpStep:Number=5) { _camera=camera; _stg=stg; _controllerHeigh=height; _gravity=gravity; _defaultGrav=gravity; _jumpStep=jumpStep; init(); } private function init():void{ _camera.y=_controllerHeigh; addListeners(); } private function addListeners():void{ _stg.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown,false,0,true); _stg.addEventListener(MouseEvent.MOUSE_UP, onMouseUp,false,0,true); _stg.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown,false,0,true); _stg.addEventListener(KeyboardEvent.KEY_UP, onKeyUp,false,0,true); } private function onMouseDown(e:MouseEvent):void{ _oldPan=_pan; _oldTilt=_tilt; _oldMouseX=_stg.mouseX+400; _oldMouseY=_stg.mouseY-300; _canMove=true; } private function onMouseUp(e:MouseEvent):void{ _canMove=false; } private function onKeyDown(e:KeyboardEvent):void{ switch(e.keyCode) { case 65:_moveLeft = true;break; case 68:_moveRight = true;break; case 87:_moveForward = true;break; case 83:_moveBack = true;break; case Keyboard.SPACE: if(_camera.y<MAX_JUMP+_controllerHeigh){ _jumpSpeed=_jumpStep; }else{ _jumpSpeed=0; } break; } } private function onKeyUp(e:KeyboardEvent):void{ switch(e.keyCode) { case 65:_moveLeft = false;break; case 68:_moveRight = false;break; case 87:_moveForward = false;break; case 83:_moveBack = false;break; case Keyboard.SPACE:_jumpSpeed=0;break; } } public function walk():void{ _camSpeed *= FRICTION_FACTOR; _camSideSpeed*= FRICTION_FACTOR; if(_moveForward){ _camSpeed+=CAM_ACCEL;} if(_moveBack){_camSpeed-=CAM_ACCEL;} if(_moveLeft){_camSideSpeed-=CAM_SIDE_ACCEL;} if(_moveRight){_camSideSpeed+=CAM_SIDE_ACCEL;} if (_camSpeed < 2 && _camSpeed > -2){ _camSpeed=0; } if (_camSideSpeed < 0.05 && _camSideSpeed > -0.05){ _camSideSpeed=0; } _forwardLook=_camera.transform.deltaTransformVector(new Vector3D(0,0,1)); _forwardLook.normalize(); _camera.x+=_forwardLook.x*_camSpeed; _camera.z+=_forwardLook.z*_camSpeed; _sideLook=_camera.transform.deltaTransformVector(new Vector3D(1,0,0)); _sideLook.normalize(); _camera.x+=_sideLook.x*_camSideSpeed; _camera.z+=_sideLook.z*_camSideSpeed; _camera.y+=_jumpSpeed; if(_canMove){ _pan = 0.3*(_stg.mouseX+400 - _oldMouseX) + _oldPan; _tilt = -0.3*(_stg.mouseY-300 - _oldMouseY) + _oldTilt; if (_tilt > 70){ _tilt = 70; } if (_tilt < -70){ _tilt = -70; } } var panRADs_Number=_pan*DEGStoRADs; var tiltRADs_Number=_tilt*DEGStoRADs; _camTarget.x = 100*Math.sin( panRADs) * Math.cos (tiltRADs) +_camera.x; _camTarget.z = 100*Math.cos( panRADs) * Math.cos (tiltRADs) +_camera.z; _camTarget.y = 100*Math.sin(tiltRADs) +_camera.y; if(_camera.y>_controllerHeigh){ _gravity*=GRAVACCEL; _camera.y-=_gravity; } if(_camera.y<=_controllerHeigh ){ _camera.y=_controllerHeigh; _gravity=_defaultGrav; } _camera.lookAt(_camTarget); } } } Now let's put it to work in the main application: FPSDemo.as package { public class FPSDemo extends AwayTemplate { [Embed(source="assets/buildings/CityScape.3ds",mimeType=" application/octet-stream")] private var City:Class; [Embed(source="assets/buildings/CityScape.png")] private var CityTexture:Class; private var _cityModel:Object3D; private var _fpsWalker:FPSController; public function FPSDemo() { super(); } override protected function initGeometry() : void{ parse3ds(); } private function parse3ds():void{ var max3ds_Max3DS=new Max3DS(); _cityModel=max3ds.parseGeometry(City); _view.scene.addChild(_cityModel); _cityModel.materialLibrary.getMaterial("bakedAll [Plane0"). material=new BitmapMaterial(Cast.bitmap(new CityTexture())); _cityModel.scale(3); _cityModel.x=0; _cityModel.y=0; _cityModel.z=700; _cityModel.rotate(Vector3D.X_AXIS,-90); _cam.z=-1000; _fpsWalker=new FPSController(_cam,stage,_view,20,12,250); } override protected function onEnterFrame(e:Event) : void{ super.onEnterFrame(e); _fpsWalker.walk(); } } } How it works... FPSController class looks a tad scary, but that is only at first glance. First we pass the following arguments into the constructor: camera: Camera3D reference (here Camera3D, by the way, is the most appropriate one for FPS). stg: References to flash stage because we are going to assign listeners to it from within the class. height: It is the camera distance from the ground. We imply here that the ground is at 0,0,0. gravity: Gravity force for jump. JumpStep: Jump altitude. Next we define listeners for mouse UP and DOWN states as well as events for registering input from A,W,D,S keyboard keys to be able to move the FPSController in four different directions. In the onMouseDown() event handler, we update the old pan, tilt the previous mouseX and mouseY values as well as by assigning the current values when the mouse has been pressed to _oldPan, _oldTilt, _oldMouseX, and _oldMouseY variables accordingly. That is a widely used technique. We need to do this trick in order to have nice and continuous transformation of the camera each time we start moving the FPSController. In the methods onKeyUp() and onKeyDown(), we switch the flags that indicate to the main movement execution code. This will be seen shortly and we will also see which way the camera should be moved according to the relevant key press. The only part that is different here is the block of code inside the Keyboard.SPACE case. This code activates jump behavior when the space key is pressed. On the SPACE bar, the camera jumpSpeed (that, by default, is zero) receives the _jumpStep incremented value and this, in case the camera has not already reached the maximum altitude of the jump defined by MAX_JUMP, is added to the camera ground height. Now it's the walk() function's turn. This method is supposed to be called on each frame in the main class: _camSpeed *= FRICTION_FACTOR; _camSideSpeed*= FRICTION_FACTOR; Two preceding lines slow down, or in other words apply friction to the front and side movements. Without applying the friction. It will take a lot of time for the controller to stop completely after each movement as the velocity decrease is very slow due to the easing. Next we want to accelerate the movements in order to have a more realistic result. Here is acceleration implementation for four possible walk directions: if(_moveForward){ _camSpeed+= CAM_ACCEL;} if(_moveBack){_camSpeed-= CAM_ACCEL;} if(_moveLeft){_camSideSpeed-= CAM_SIDE_ACCEL;} if(_moveRight){_camSideSpeed+= CAM_SIDE_ACCEL;} The problem is that because we slow down the movement by continuously dividing current speed when applying the drag, the speed value actually never becomes zero. Here we define the range of values closest to zero and resetting the side and front speeds to 0 as soon as they enter this range: if (_camSpeed < 2 && _camSpeed > -2){ _camSpeed=0; } if (_camSideSpeed < 0.05 && _camSideSpeed > -0.05){ _camSideSpeed=0; } Now we need to create an ability to move the camera in the direction it is looking. To achieve this we have to transform the forward vector, which present the forward look of the camera, into the camera space denoted by _camera transformation matrix. We use the deltaTransformVector() method as we only need the transformation portion of the matrix dropping out the translation part: _forwardLook=_camera.transform.deltaTransformVector(new Vector3D(0,0,1)); _forwardLook.normalize(); _camera.x+=_forwardLook.x*_camSpeed; _camera.z+=_forwardLook.z*_camSpeed; Here we make pretty much the same change as the previous one but for the sideways movement transforming the side vector by the camera's matrix: _sideLook=_camera.transform.deltaTransformVector(new Vector3D(1, 0,0)); _sideLook.normalize(); _camera.x+=_sideLook.x*_camSideSpeed; _camera.z+=_sideLook.z*_camSideSpeed; And we also have to acquire base values for rotations from mouse movement. _pan is for the horizontal (x-axis) and _tilt is for the vertical (y-axis) rotation: if(_canMove){ _pan = 0.3*(_stg.mouseX+400 - _oldMouseX) + _oldPan; _tilt = -0.3*(_stg.mouseY-300 - _oldMouseY) + _oldTilt; if (_tilt > 70){ _tilt = 70; } if (_tilt < -70){ _tilt = -70; } } We also limit the y-rotation so that the controller would not rotate too low into the ground and conversely, too high into zenith. Notice that this entire block is wrapped into a _canMove Boolean flag that is set to true only when the mouse DOWN event is dispatched. We do it to prevent the rotation when the user doesn't interact with the controller. Finally we need to incorporate the camera local rotations into the movement process. So that while moving, you will be able to rotate the camera view too: var panRADs_Number=_pan*DEGStoRADs; var tiltRADs_Number=_tilt*DEGStoRADs; _camTarget.x = 100*Math.sin( panRADs) * Math.cos(tiltRADs) + _camera.x; _camTarget.z = 100*Math.cos( panRADs) * Math.cos(tiltRADs) + _camera.z; _camTarget.y = 100*Math.sin(tiltRADs) +_camera.y; And the last thing is applying gravity force each time the controller jumps up: if(_camera.y>_controllerHeigh){ _gravity*=GRAVACCEL; _camera.y-=_gravity; } if(_camera.y<=_controllerHeigh ){ _camera.y=_controllerHeigh; _gravity=_defaultGrav; } Here we first check whether the camera y-position is still bigger than its height, this means that the camera is in the "air" now. If true, we apply gravity acceleration to gravity because, as we know, in real life, the falling body constantly accelerates over time. In the second statement, we check whether the camera has reached its default height. If true, we reset the camera to its default y-position and also reset the gravity property as it has grown significantly from the acceleration addition during the last jump. To test it in a real application, we should initiate an instance of the FPSController class. Here is how it is done in FPSDemo.as: _fpsWalker=new FPSController(_cam,stage,20,12,250); We pass to it our scene camera3D instance and the rest of the parameters that were discussed previously. The last thing to do is to set the walk() method to be called on each frame: override protected function onEnterFrame(e:Event) : void{ super.onEnterFrame(e); _fpsWalker.walk(); } Now you can start developing the Away3D version of Unreal Tournament!
Read more
  • 0
  • 0
  • 1655
article-image-away3d-detecting-collisions
Packt
02 Jun 2011
6 min read
Save for later

Away3D: Detecting Collisions

Packt
02 Jun 2011
6 min read
Away3D 3.6 Cookbook Over 80 practical recipes for creating stunning graphics and effects with the fascinating Away3D engine Introduction In this article, you are going to learn how to check intersection (collision) between 3D objects. Detecting collisions between objects in Away3D This recipe will teach you the fundamentals of collision detection between objects in 3D space. We are going to learn how to perform a few types of intersection tests. These tests can hardly be called collision detection in their physical meaning, as we are not going to deal here with any simulation of collision reaction between two bodies. Instead, the goal of the recipe is to understand the collision tests from a mathematical point of view. Once you are familiar with intersection test techniques,the road to creating of physical collision simulations is much shorter. There are many types of intersection tests in mathematics. These include some simple tests such as AABB (axially aligned bounding box), Sphere - Sphere, or more complex such as Triangle - Triangle, Ray - Plane, Line - Plane, and more. Here, we will cover only those which we can achieve using built-in Away3D functionality. These are AABB and AABS (axially aligned bounding sphere) intersections, as well as Ray-AABS and the more complex Ray- Triangle. The rest of the methods are outside of the scope of this article and you can learn about applying them from various 3D math resources. Getting ready Setup an Away3D scene in a new file extending AwayTemplate. Give the class a name CollisionDemo. How to do it... In the following example, we perform an intersection test between two spheres based on their bounding boxes volumes. You can move one of the spheres along X and Y with arrow keys onto the second sphere. On the objects overlapping, the intersected (static) sphere glows with a red color. AABB test: CollisionDemo.as package { public class CollisionDemo extends AwayTemplate { private var _objA:Sphere; private var _objB:Sphere; private var _matA:ColorMaterial; private var _matB:ColorMaterial; private var _gFilter_GlowFilter=new GlowFilter(); public function CollisionDemo() { super(); _cam.z=-500; } override protected function initMaterials() : void{ _matA=new ColorMaterial(0xFF1255); _matB=new ColorMaterial(0x00FF11); } override protected function initGeometry() : void{ _objA=new Sphere({radius:30,material:_matA}); _objB=new Sphere({radius:30,material:_matB}); _view.scene.addChild(_objA); _view.scene.addChild(_objB); _objB.ownCanvas=true; _objA.debugbb=true; _objB.debugbb=true; _objA.transform.position=new Vector3D(-80,0,400); _objB.transform.position=new Vector3D(80,0,400); } override protected function initListeners() : void{ super.initListeners(); stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown); } override protected function onEnterFrame(e:Event) : void{ super.onEnterFrame(e); if(AABBTest()){ _objB.filters=[_gFilter]; }else{ _objB.filters=[]; } } private function AABBTest():Boolean{ if(_objA.parentMinX>_objB.parentMaxX||_objB.parentMinX>_objA. parentMaxX){ return false; } if(_objA.parentMinY>_objB.parentMaxY||_objB.parentMinY>_objA. parentMaxY){ return false; } if(_objA.parentMinZ>_objB.parentMaxZ||_objB.parentMinZ>_objA. parentMaxZ){ return false; } return true; } private function onKeyDown(e:KeyboardEvent):void{ switch(e.keyCode){ case 38:_objA.moveUp(5); break; case 40:_objA.moveDown(5); break; case 37:_objA.moveLeft(5); break; case 39:_objA.moveRight(5); break; case 65:_objA.rotationZ-=3; break; case 83:_objA.rotationZ+=3; break; default: } } } } In this screenshot, the green sphere bounding box has a red glow while it is being intersected by the red sphere's bounding box: How it works... Testing intersections between two AABBs is really simple. First, we need to acquire the boundaries of the object for each axis. The box boundaries for each axis of any Object3D are defined by a minimum value for that axis and maximum value. So let's look at the AABBTest() method. Axis boundaries are defined by parentMin and parentMax for each axis, which are accessible for each object extending Object3D. You can see that Object3D also has minX,minY,minZ and maxX,maxY,maxZ. These properties define the bounding box boundaries too, but in objects space and therefore aren't helpful in AABB tests between two objects. So in order for a given bounding box to intersect a bounding box of other objects, three conditions have to be met for each of them: Minimal X coordinate for each of the objects should be less than maximum X of another. Minimal Y coordinate for each of the objects should be less than maximum Y of another. Minimal Z coordinate for each of the objects should be less than maximum Z of another. If one of the conditions is not met for any of the two AABBs, there is no intersection. The preceding algorithm is expressed in the AABBTest() function: private function AABBTest():Boolean{ if(_objA.parentMinX>_objB.parentMaxX||_objB.parentMinX>_objA. parentMaxX){ return false; } if(_objA.parentMinY>_objB.parentMaxY||_objB.parentMinY>_objA. parentMaxY){ return false; } if(_objA.parentMinZ>_objB.parentMaxZ||_objB.parentMinZ>_objA. parentMaxZ){ return false; } return true; } As you can see, if all of the conditions we listed previously are met, the execution will skip all the return false blocks and the function will return true, which means the intersection has occurred. There's more... Now let's take a look at the rest of the methods for collision detection, which are AABS-AABS, Ray-AABS, and Ray-Triangle. AABS test The intersection test between two bounding spheres is even simpler to perform than AABBs. The algorithm works as follows. If the distance between the centers of two spheres is less than the sum of their radius, then the objects intersect. Piece of cake! Isn't it? Let's implement it within the code. The AABS collision algorithm gives us the best performance. While there are many other even more sophisticated approaches, try to use this test if you are not after extreme precision. (Most of the casual games can live with this approximation). First, let's switch the debugging mode of _objA and _objB to bounding spheres. In the last application we built, go to the initGeometry() function and change: _objA.debugbb=true; _objB.debugbb=true; To: _objA.debugbs=true; _objB.debugbs=true; Next, we add the function to the class which implements the algorithm we described previously: private function AABSTest():Boolean{ var dist_Number=Vector3D.distance(_objA.position,_objB. position); if(dist<=(_objA.radius+_objB.radius)){ return true; } return false; } Finally, we add the call to the method inside onEnterFrame(): if(AABSTest()){ _objB.filters=[_gFilter]; }else{ _objB.filters=[]; } Each time AABSTest returns true, the intersected sphere is highlighted with a red glow:
Read more
  • 0
  • 0
  • 1675

article-image-importing-3d-formats-away3d
Packt
31 May 2011
5 min read
Save for later

Importing 3D Formats into Away3D

Packt
31 May 2011
5 min read
Away3D 3.6 Cookbook Over 80 practical recipes for creating stunning graphics and effects with the fascinating Away3D engine Introduction The Away3D library contains a large set of 3D geometric primitives such as Cube, Sphere, Plane, and many more. Nevertheless, when we think of developing breathtaking and cutting edge 3D applications, there is really no way to get it done without using more sophisticated models than just basic primitives. Therefore, we need to use external 3D modeling programs such as Autodesk 3DsMax and Maya, or Blender to create complex models. The Power of Away3D is that it allows us to import a wide range of 3D formats for static meshes as well as for animations. Besides the models, the not less important part of the 3D world is textures. They are critical in making the model look cool and influencing the ultimate user experience. In this article, you will learn essential techniques to import different 3D formats into Away3D. Exporting models from 3DsMax/Maya/Blender You can export the following modeling formats from 3D programs: (Wavefront), Obj, DAE (Collada), 3ds, Ase (ASCII), MD2, Kmz, 3DsMax, and Maya can export natively Obj, DAE, 3ds, and ASCII. One of the favorite 3D formats of Away3D developers is DAE (Collada), although it is not the best in terms of performance because the file is basically an XML which becomes slow to parse when containing a lot of data. The problem is that although 3DsMax and Maya have got a built-in Collada exporter, the models from the output do not work in Away3D. The work around is to use open source Collada exporters such as ColladaMax/ColladaMaya, OpenCollada. The only difference between these two is the software versions support. Getting ready Go to http://opencollada.org/download.html and download the OpenCollada plugin for the appropriate software (3DsMax or Maya). Go to http://sourceforge.net/projects/colladamaya/files/ and download the ColladaMax or colladamaya plugin. Follow the instructions of the installation dialog of the plugin. The plugin will get installed automatically in the 3dsMax/Maya plugins directory (taking into account that the software was installed into the default path). How to do it... 3DsMax: Here is how to export Collada using OpenCollada plugin in 3DsMax2011. In order to export Collada (DAE) from 3DsMax, you should do the following: In 3DsMax, go to File and click on Export or Export Selected (target model selected). Select the OpenCOLLADA(*.DAE) format from the formats drop-down list. ColladaMax export settings: (Currently 3DsMax 2009 and lower) ColladaMax export settings are almost the same as those of OpenCollada. The only difference you can see in the exporting interface is the lack of Copy Images and Export user defined properties checkboxes. Select the checkboxes as is shown in the previous screenshot. Relative paths: Makes sure the texture paths are relative. Normals: Exporting object's normals. Copy Images: Is optional. If we select this option, the exporter outputs a folder with related textures into the same directory as the exported object. Triangulate: In case some parts of the mesh consist of more than three angled polygons, they get triangulated. Animation settings: Away3D supports bones animations from external assets. If you set bones animation and wish to export it, then check the Sample animation and set the begin and end frame for animation span that you want to export from the 3DsMax animation timeline. Maya: For showcase purposes, you can download a 30-day trial version of Autodesk Maya 2011. The installation process in Maya is slightly different: Open Maya. Go to top menu bar and select Window. In the drop-down list, select Settings/Preferences, in the new drop-down list, select Plug-in manager. Now you should see the Plug-in Manager interface: Now click on the Browse button and navigate to the directory where you extracted the OpenCollada ZIP archive. Select the COLLADAMaya.mll file and open it. Now you should see the OpenCollada plugin under the Other Registered Plugins category. Check the AutoLoad checkbox if you wish for the plugin to be loaded automatically the next time you start the program. After your model is ready for export, click on File | Export All or Export selected. The export settings for ColladaMaya are the same as for 3DsMax. How it works... The Collada file is just another XML but with a different format name (.dae). When exporting a model in a Collada format, the exporter writes into the XML nodes tree all essential data describing the model structure as well as animation data when one exports bone-based animated models. When deploying your DAE models to the web hosting directory, don't forget to change the .DAE extension to .XML. Forgetting will result in the file not being able to load because .DAE extension is ignored by most servers by default. There's more... Besides the Collada, you can also export OBJ, 3Ds, and ASE. Fortunately, for exporting these formats, you don't need any third party plugins but only those already located in the software. Free programs such as Blender also serve as an alternative to expansive commercial software such as Maya, or 3DsMax Blender comes with already built-in Collada exporter. Actually, it has two such exporters. At the time of this writing, these are 1.3 and 1.4. You should use 1.4 as 1.3 seems to output corrupted files that are not parsed in Away3D. The export process looks exactly like the one for 3dsMax. Select your model. Go to File, then Export. In the drop-down list of different formats, select Collada 1.4. The following interface opens: Select Triangles, Only Export Selection (if you wish to export only selected object), and Sample Animation. Set exporting destination path and click on Export and close. You are done.
Read more
  • 0
  • 0
  • 2451