官术网_书友最值得收藏!

Using the terrain editor

In building any game that involves an outdoor environment, a terrain editor is a must-have for any game developer. Unity has featured a built-in terrain editor since version 2.0, and this makes building complete environments quick and easy.

In Unity terms, think of a terrain as simply a game object that has a terrain toolkit component applied to it. Beginning as a Plane—a flat, single-sided 3D shape—the terrain you'll create shortly can be transformed into a complete set of realistic geometry, with additional details such as trees, rocks, foliage, and even atmospheric effects such as wind speed.

Terrain menu features

In order to take a look at the features outlined below, you will need to create a terrain. So let's begin by introducing a new terrain object to the game—this is an Asset that can be created within Unity, so simply go to Terrain | Create Terrain from the top menu.

Before you can begin to modify your terrain, you should set up various settings for size and detail. The Terrain menu at the top of Unity allows you to not only create a terrain for your game, but also perform the following operations:

Importing and exporting heightmaps

Heightmaps are 2D graphics with light and dark areas to represent terrain topography and can be imported as an alternative to using Unity's height painting tools.

Created in an art package such as Photoshop and saved in a .RAW format, heightmaps are often used in game development, as they can be easily exported and transferred between art packages and development environments such as Unity.

As we will be using the Unity Terrain tools to create our environment, we will not be utilizing externally created heightmaps as part of this book.

Set Heightmap resolution

Set Heightmap resolution

The given dialog window allows you to set a number of properties for the new terrain you have made. These settings should always be adjusted before the topography of the terrain is created, as adjusting them later can cause work on the terrain to be reset.

  • Terrain Width, Height and Length: Measured in meters. Note that Height here sets the maximum height that the terrain's topography can feature.
  • Heightmap Resolution: The resolution of the texture that Unity stores to represent the topography in pixels. Note that although most textures in Unity must be a power of two dimension—128, 256, 512 and so on, heightmap resolutions always add an extra pixel because each pixel defines a vertex point; so in the example of a 4 x 4 terrain, four vertices would be present along each section of the grid, but the points at which they meet—including their endpoints—would equal five.
  • Detail resolution: The resolution of the graphic, known as a Detail resolution map, that Unity stores. This defines how precisely you can place details on the terrain. Details are additional terrain features such as plants, rocks, and bushes. The larger the value, the more precisely you can place details on the terrain in terms of positioning.
  • Control Texture Resolution: The resolution of textures when painted onto the terrain. Known as Splatmap textures in Unity, the Control Texture Resolution value controls the size and, therefore, the detail of any textures you paint on. As with all texture resolutions, it is advisable to keep this figure lower to increase performance. With this in mind, it is a good practice to leave this value set to its default of 512.
  • Base Texture Resolution: The resolution of the texture used by Unity to render terrain areas in the distance that are further from the in-game camera or on older performance hardware.

Creating the lightmap

Creating the lightmap

This dialog is used to bake (semi-permanently render) the lighting of topography onto the textures that make up its appearance. For example, if we created a small hilly terrain and then wished to include a mountain in the middle, then we would use the terrain tools to create the mountain. However, given the shadow cast on the terrain by this new mountain, we would need to re-create the lightmap to render the dark areas onto the textures in the newly shaded area of our terrain.

Utilizing the lights area of this dialog allows you to increase the number of lights used to render the lightmap. For example, our scene may be lit mostly by a Directional light, which acts as sunlight from a certain direction. Some Point lights may be included also, such as those representing outdoor lamps or fires.

As you create new topography when using the terrain tools, the create lightmap function is an example of one you may need to revisit as your landscape changes. By creating a lightmap to map light and dark areas on the terrain, you are also saving on processing power when the game runs, as you have already calculated part of the lighting. This is in opposition to dynamic lighting for the terrain, which is more expensive in processing terms.

Mass Place Trees

This function does exactly what its name says—placing a specified number of trees onto the terrain, with specific tree and associated parameters specified in the Place Trees area of the terrain script component in the Inspector.

This function is not recommended for general use, as it gives you no control over the position of the trees. I recommend that you use the Place Trees part of the terrain script instead, in order to manually paint a more realistic placement.

Flatten Heightmap

Flatten Heightmap is present to allow you to flatten the entire terrain at a certain height. By default, your terrain height begins at zero, so if you wish to make a terrain with a default height above this, such as we do for our island, then you can specify the height value here.

Refresh Tree and Detail Prototypes

If you make changes to the assets that make up any trees and details that have already been painted onto the terrain, then you'll need to select Refresh Tree and Detail Prototypes to update them on the terrain.

The terrain toolset

Before we begin to use them to build our island, let's take a look at the terrain tools so that you can familiarize yourself with their functions.

As you have just created your terrain, it should be selected in the Hierarchy window. If it is not selected, then select it now in order to show its properties in the Inspector.

Terrain Script

On the Inspector, the terrain toolset is referred to in component terms as the Terrain (Script). The Terrain (Script) component gives you the ability to utilize the various tools and specify settings for the terrain in addition to the functions available in the terrain menu outlined above.

In the following screenshot, you can see that this is the second of three components on the Terrain game object (the others being Transform and Terrain Collider).

Terrain Script

The Terrain (Script) component has seven sections to it, which are easily accessible from the icon buttons at the top of the component. Before we begin, here is a quick overview of their purpose in building terrains.

Raise Height

This tool allows you to raise areas by painting with the Transform tool (Shortcut—W key).

Terrain (Script) componentaboutRaise Height

You also have the ability to specify Brush styles, Size, and Opacity (effectiveness) for the deformation you make. Holding the Shift key while using this tool causes the opposite effect—lowering height.

Terrain (Script) componentaboutRaise Height

Paint height

This tool works similarly to the Raise Height tool, but gives you an additional setting—height.

Paint height

This means that you can specify a height to paint towards, which means that when the area of the terrain that you are raising reaches the specified height, it will flatten out, allowing you to create plateaus, as shown in the following screenshot:

Paint height

Smooth height

This tool is used mostly to complement other tools such as Paint Height in order to soften harsh areas of topography.

Smooth height

For example, in the previous plateau, the land goes straight up, and should I wish to soften the edges of the raised area, I would use this tool to round off the harsh edges, creating the result shown in the following screenshot:

Smooth height

Paint Texture

Paint Texture is the tool used to brush textures—referred to as Splats in Unity terrain terms—onto the surface of the terrain

Paint Texture

In order to paint with textures, the textures must first be added to the palette in the Textures area of this tool. Textures can be added by clicking on the Edit Textures button and selecting Add Texture, which will allow you to choose any texture file currently in your project, along with parameters for tiling the chosen texture.

The next screenshot is an example of this tool with three textures in the palette. The first texture you add to the palette will be painted over the entire terrain by default. Then, by combining several textures at varying opacities and painting manually onto the terrain, you can get some realistic areas of whatever kind of surface you're hoping to get.

To choose a texture to paint with, simply click on its preview in the palette. The currently chosen texture is highlighted with a blue outline.

Paint Texture

Place Trees

This is another tool that does what its name suggests. By brushing with the mouse, or using single clicks, Place Trees can be used to paint trees onto the terrain, having specified which asset to use when painting.

Place Trees

In the same way as specifying textures for the Paint Texture tool, this tool gives you an Edit Trees button to add, edit, and remove assets from the palette.

In its Settings, you can specify:

  • Brush Size: The amount of trees to paint per click
  • Tree Density: The proximity of trees placed when painting
  • Color Variation: Applies random color variation to trees when painting several at once
  • Tree Width/Height: Sizes the tree asset you are painting with
  • Tree Width/Height Variation: Gives you random variation in sizing to create more realistically forested areas

This tool also utilizes the Shift key to reverse its effects. In this instance, using Shift erases painted trees and can be used in conjunction with the Ctrl key to only erase trees of the type selected in the palette.

Paint Details

This tool works in a similar manner to the Place Trees tool but is designed to work with detail objects such as flowers, plants, rocks, and other foliage.

Paint Details

Terrain Settings

The Terrain Settings area of the Terrain (Script) contains various settings for the drawing of the terrain by the computer's GPU (graphical processing unit).

Terrain Settings

Here you can specify various settings that affect the Level of Detail (LOD).

Level of Detail in game development defines the amount of detail specified within a certain range of a player. In this example—a terrain—we need to be able to adjust settings such as Draw Distance, which is a common 3D game concept that renders less detail after a certain distance from the player in order to improve performance.

In Terrain Settings, for example, you can adjust Base Map Distance in order to specify how far away until the terrain replaces high resolution graphics for lower resolution ones, making objects in the distance less expensive to render.

The following screenshot is an example of a low Base Map Distance of around 10 meters. As you can see, the textures further than the specified distance are drawn at far lower detail.

Terrain Settings

We'll look at the Terrain script's settings further as we begin to build our terrain.

Sun, Sea, Sand—creating the island

Step 1—Terrain setup

Now that we have looked at the tools available to create our terrain, let's get started by setting up our terrain using the Terrain top menu. Ensure that your Terrain is still selected in the Hierarchy, and go to Terrain | Set Resolution.

As we don't want to make too large an island for our first project, set the terrain width and length both to 1000. Remember to press Enter after typing these values in so that you've effectively confirmed them before clicking on Import.

Next, our island's height needs to begin at its ground level, rather than at zero, which is the default for new terrains. If you consider that the terrain height of zero should be the sea bed, then we can say that our ground level should be raised to be the surface height of the island. Go to Terrain | Flatten Heightmap.

Click inside the Height box, and place in a value of 30 meters, and then press Enter to confirm. Click on Flatten to finish.

This change is a blink-and-you'll-miss-it difference in the Scene view, as all we've done is shift the terrain upward slightly. However, the reason we've done this is that it is a great time saver—as we can now flatten around the edges of the terrain using inverse Raise Height to leave a raised island in the centre of the terrain. This is a more time-efficient method than beginning with a flat island and raising the height in the centre.

Step 2—Island outline

On the Inspector for the Terrain object's Terrain (Script) component, choose the Raise Height tool—the first of the seven buttons.

Select the first brush in the palette, and set its Brush Size to 75. Set Opacity for the brush to 0.5.

Change your view in the Scene panel to a top-down view by clicking on the Y-axis (green spoke) of the view gizmo in the top-right.

terrain, island demo projectterrain, setting upStep 2—Island outline

Using the Shift key to lower height, paint around the outline of the terrain, creating a coastline that descends to zero height—you will know it has reached zero as the terrain will flatten out at this minimum height.

While there is no need to match the outline of the island I have created, try not to make a wildly different shape either, as you will need a flat expanse of land later. Once you have painted around the entire outline, it should look something like this:

terrain, island demo projectterrain, setting upStep 2—Island outline

Now switch back to a perspective (3D) view of your Scene by clicking on the center cube of the view gizmo in the top-right of the Scene window and admire your handiwork. If you are unsure, here is what mine looks like:

terrain, island demo projectterrain, setting upStep 2—Island outline

Now spend some time going over the island, using the Raise Height tool to create some further topographical detail, and perhaps using Lower Height (with the Shift key) to add an inlet or lake. Leave a flat area in the center of your terrain and one free corner of your map in which we are going to add a volcano!

Step 3—Volcano!

Now to create our volcano! For this we will combine the use of the Paint Height, Raise Height, and Smooth Height tools. First, select the Paint Height tool.

Choose the first brush in the palette, and set the Brush Size to 75, Opacity to 0.5. and Height to 200. Select the Top view again using the view gizmo, and paint on a plateau in the corner that you left free on your terrain. Remember that this tool will stop affecting the terrain once it reaches the specified height of 200.

Your island should now look like this in the perspective view:

Step 3—Volcano!

Now this plateau may look clunky—we'll rectify this with smoothing shortly, but first we need to create the volcano mouth. So now with the Paint Height tool still selected, change the Height setting to 20 and the Brush Size to 30.

Now hold down the mouse and start painting from the center of the plateau outwards towards its edge in every direction, until you have effectively hollowed out the plateau, leaving a narrow ridge around its circumference, as shown in the following screenshot:

Step 3—Volcano!

We still have a fairly solid edge to this ridge, and when switching to the perspective view, you'll see that it still doesn't look quite right. This is where the Smooth Height tool comes in. Select the Smooth Height tool and set the Brush Size to 30 and Opacity to 1. Using this tool, paint around the edge of the ridge with your mouse, softening its height until you have created a rounded soft ridge, as shown in the following screenshot:

Step 3—Volcano!

Now that our volcano has started to take shape, we can begin to texture the island to add realism to our terrain.

Step 4—Adding textures

When texturing your terrain, it is crucial to remember that the first texture you add will cover the terrain entirely. With this in mind, you should ensure that the first texture you add to your texture palette is the texture which represents the majority of your terrain.

In the Standard Assets Package we included when we started the project, we are given various assets with a variety of game features to get started with. As such, you'll find a folder called Standard Assets in your Project panel. Expand this down by clicking on the gray arrow to the left of it, and then expand the subfolder called Terrain Textures.

Step 4—Adding textures

These are the four textures we'll use to paint our island terrain, so we'll begin by adding them to our palette. Ensure that the Terrain game object is still selected in the screenshot, and then select the Paint Texture tool from the Terrain (Script) component in the Inspector.

Painting procedure

To introduce the four textures for our terrain, begin by clicking on the Edit Textures button, and select Add Textures from the menu that pops out. This will launch the Add Textures dialog window in which you can select any texture currently in your project. Click on the down arrow to the right of the Splat setting to choose from a list of all available textures, and select the texture called Grass (Hill).

terrain, island demo projecttextures, addingPainting procedure

Leave the Tile Size X and Y values on 15 here, as this texture will cover the entire map, and this small value will give us a more detailed-looking grass. Click on Add to finish. This will cover your terrain with the grass texture, as it is the first one we have added. Any future textures added to the palette will need to be painted on manually.

Repeat the previous step to add three further textures to the palette, choosing the textures named Grass&Rock, Cliff (Layered Rock), and GoodDirt—while leaving the Tile Size settings unchanged for all except the Cliff (Layered Rock) texture, which should have an X and Y Tile Size of 70, as it will be applied to a stretched area of the map and will look distorted unless tiled at a larger scale.

terrain, island demo projecttextures, addingPainting procedure
Sandy areas

You should now have all four textures available in your palette. Matching the above settings, choose the last texture added—GoodDirt—and it should become highlighted by a blue underline as shown. Set the Brush Size to 60, Opacity to 0.5, and Target Strength to 1. You can now paint around the coast of the island using either the Top or Perspective view.

If you are using the Perspective view to paint textures, it will help to remember that you can use the Alt key while dragging the mouse, with either the Hand (Shortcut—Q) or Transform (Shortcut—W) tools selected, in order to rotate your view.

When finished, you should have something like this:

Sandy areas

If you make a mistake while painting, you can either use Edit | Undo to step back one brush stroke, that is, a single-0.held mouse click, or select the texture from the palette that you do want to be where you accidentally painted, and re-paint with that.

Grass & Rock

Next select the Grass & Rock texture by clicking on the second thumbnail added. Set the Brush Size to 25, Opacity to 0.3, and Target Strength to 0.5. Now brush over any hilly areas on your terrain and around the top half of the volcano until you have created something like this:

Grass & Rock
Volcanoes Rock!

Now we need to make our volcano look more realistic by adding the Cliff (Layered Rock) texture to it. Select the cliff texture from the palette, and set the Brush Size to 25 and both Opacity and Target Strength to 1.

Paint over the top outer half and the entire inner with these settings and then slowly decrease the Opacity and Brush Size values as you work your way down the outside of the volcano so that this texture is applied more subtly towards the ground. With a lower opacity, you may also want to paint over the tops of some of your taller hilled areas on the terrain.

While this will take some experimentation, when finished, your volcano should look something like this:

Volcanoes Rock!

Step 5—Tree time

Now that we have a fully textured island, we need to spruce up the place a little with some trees. In our Standard Assets package, there is a tree provided to get us started with the terrain editor, and thankfully for us, it is a palm tree asset.

Select the Place Trees section of the Terrain (Script) component, and click on the Edit Trees button. From the drop-down menu that appears, choose Add Tree.

The Add Tree dialog window appears. As with some of the other terrain tools, this Add dialog allows us to select from any object of an appropriate type from our Assets folder.

This is not restricted to trees provided in Standard Assets, which means that you can model your own trees by saving them into the Assets folder of your project in order to use them with this tool. However, we are going to use the Standard Assets provided palm tree. So select the Palm asset by clicking on the down arrow to the right of the Tree setting.

Bend Factor here allows our trees to sway in the wind. This effect is computationally expensive, so we'll simply use a low number. Type in a value of 2 and press Enter to confirm. If you find that this is causing low performance later in development, then you can always return to this setting and set it back to zero. Click on the Add button to finish.

With your palm tree in the palette, you should see a small preview of the tree with a blue background to show that it is selected as the tree to place.

Set the Brush Size to 15 (painting 15 trees at a time) and the Tree Density to 0 (giving us a wide spread of trees). Set Color Variation to 0.4 to give us a varied set of trees and Tree Height / Width to 1.5 with their Variation settings to 0.3.

Using single-clicks, place trees around the coast of the island, near the sandy areas that you would expect to see them. Then to complement the island's terrain, place a few more palm trees at random locations inland.

Remember that if you paint trees incorrectly at any time, you can hold the Shift key and click, or paint (drag) with the mouse to erase trees from the terrain.

Step 6—Grassed up

Now that we have some trees on our island, we'll add a small amount of grass to complement the grass textures we covered the terrain with.

Select the Paint Details section of the Terrain (Script) component and click on the Edit Details button. Select Add Grass Texture from the pop-up menu.

The Standard Assets package provides us with a grass texture to use, so from the drop-down menu to the right of the Detail Texture setting, select the texture simply called Grass.

Having chosen the Grass texture, leave the Width and Height values at their default and ensure that Billboard is selected at the bottom of this dialog. As our grass detail textures are 2D, we can employ billboarding, a technique in game development that rotates the grass texture to face the camera during game play in order to make the grass seem less two-dimensional.

Using the color-picker boxes, ensure that the Healthy and Dry colors are of a similar shade of green to the textures we have painted onto the terrain, because leaving them on the default bright green will look out of place.

Step 6—Grassed up

Click on the Add button at the bottom of the dialog window to confirm adding this texture to your palette.

To paint grass onto our map, we can yet again use mouse-based brushing in a similar way to the other terrain tools. Firstly, we'll need to choose a brush and settings in order to ensure a wide and disparate painting of grass detail onto our map. Given that rendering grass is another expensive feature for the computer to render, we'll keep the grass to a minimum by setting the Brush Size to 100, but Opacity to 0.05, and Target Strength to 0.6. This will give a wide spread with very little grass, and by choosing a stipple brush (see the next screenshot) we can paint on patchy areas of grass.

Step 6—Grassed up

Now zoom into the terrain surface by selecting the Hand tool, and holding the Command key (Mac) or the Ctrl key (PC) while dragging the mouse to the right. Once at a close level of zoom, you'll be able to click the mouse to paint on areas of grass. Move around the island painting on a few grassy areas—do this sparingly for performance reasons—and later you can always come back and add more grass if the game performs well.

Tip

It is crucial to zoom in on your terrain while painting details as the Unity Editor's Scene view does not render them visibly when zoomed out in order to save memory—so often it'll seem that when you have zoomed out, your grass and other details will disappear—do not worry, this is not the case.

Step 7—Let there be lights!

Now that our island terrain is ready to explore, we'll need to add lighting to our scene. When first approaching lighting in Unity, it's best to be aware of what the three different light types are used for:

  • Directional light: Used as the main source of light, often as sunlight, a Directional light does not emanate from a single point, but instead simply travels in a single direction.
  • Point light: These lights emanate from a single point in the 3D world and are used for any other source of light, such as indoor lighting, fires, glowing objects, and so on.
  • Spot light: Exactly what it sounds like, this light shines in a single direction but has a radius value that can be set, much like focusing a flashlight.
Creating sunlight

To introduce our main source of light, we'll add a Directional light. Go to GameObject | Create Other | Directional Light. This adds the light as an object in our scene, and you will see that it is now listed in the Hierarchy.

As the Directional light does not emanate from a point, its position is ordinarily irrelevant as it cannot be seen by the player—only the light it casts is seen. However, in this tutorial, we're going to use the Directional light to represent the sun, by applying a light Flare to the light.

In order to represent the sun, we'll position the light high above the island, and to ensure that it is consistent with the direction of the light it casts, we'll position the light away from the island in the Z-axis.

Position the light at (0, 500, -200) by typing in the Inspector Transform boxes and pressing Enter to confirm each value set. Set the X rotation to 8 in order to tilt the light downward in the X-axis, and this will cast more light onto our terrain.

Finally, we'll need to make the light visible. To do this, choose a light flare by clicking on the drop-down arrow to the right of the Flare setting in the Light component—it will currently be set to None, but instead, choose Sun.

Creating sunlight

Step 8—What's that sound?

An oft-overlooked area of game development is sound. For a truly immersive experience, your player needs to not only see the environment you've made, but hear it too.

Sound in Unity is handled through 2 components, the Audio Source, and the Audio Listener. Think of the Source as a speaker in your game world, and the Listener as a microphone or the player's ear. By default, camera game objects in Unity have an audio listener component. So given that you always have a camera in your game, chances are you'll only ever have to set up sound sources. It is also worth noting that the Audio Listener component has no properties to adjust—it just works—and that Unity will inform you with an error if you accidentally remove the only listener in any scene.

Stereo versus Mono

Unity handles the behavior of sound by utilizing Stereo (two-channel) sound as constant volume, and Mono (single channel) sound as variable volume, based upon its source's proximity to the listener in the 3D world.

For example, for the following purposes:

  • In game music: Stereo sound would be best, as it would remain constant no matter where the player's listener goes in the game.
  • Sound effect of a Hi-Fi inside a building: Mono sound would be best—although you may be playing music as your sound effect, using mono sound files would allow the sound source to become louder, the closer the player gets to it.
Formats

Unity will accept the most common audio formats—WAV, MP3, AIFF, and OGG. Upon encountering a compressed format such as MP3, Unity converts your audio file to the Ogg Vorbis file format, while leaving uncompressed sounds such as WAVs unconverted.

As with other assets you import, audio files simply get converted as soon as you switch between another program and Unity, as Unity scans the contents of the Assets folder each time you switch to it to look for new files.

The hills are alive!

To make our island feel more realistic, we'll add a sound source playing outdoor ambience using a stereo sound.

Begin by selecting the Terrain object in the Hierarchy. Go to Component | Audio | Audio Source from the top menu. This adds an Audio Source component to the terrain. As the volume remains constant when using stereo sounds, and position is irrelevant, we could place the ambience sound source on any object—it simply makes logical sense that ambient sound of the terrain should be attached to that game object.

In the Inspector of the terrain, you will now see the Audio Source component with which you may either choose a file to play or leave blank if you are planning to play sounds through scripting.

Importing your first package

For this step, you'll need to download the first of several asset packages from the Packt publishing web site, www.packtpub.com/files/8181_Code.zip. Locate the file called Sound1.unitypackage from the list of files associated with this book and then return to Unity and go to Assets | Import Package.

You will be presented with a file selection Import Package dialog, from which you should navigate to the location on your hard drive that you saved the downloaded file. Select it, and then click on Open to choose it. Unity will then present you with a list of assets that are contained in the package—by default it assumes that the user wants to import all assets in the package, but the ability to only import certain assets is useful when extracting single files from larger packages.

In our Sound1 package, there is simply a single MP3 format sound file called hillside.mp3—along with a folder called Sound to keep it in—so you will only see those two files.

Click on Import to confirm adding these files to your project and after a short conversion progress bar, you should see them in your project panel—you'll need to open the Sound folder you've added by clicking on the gray arrow to the left of it in order to see the hillside sound file. Sound files are represented in your Project panel by the speaker icon, as shown in the following screenshot:

Importing your first package

The hillside file is now ready to be applied to the Audio Source component of the terrain.

Click on the down arrow to the right of the Audio Clip setting in the Audio Source component of the terrain game object. This will show you a list of all available audio files in your project. As we only have the hillside audio file in ours, that is all you will see on this drop-down menu, so select it now.

Further audio settings

The Audio Source component has various settings to control how the audio clip sounds, as well as how it plays back. For our ambient hillside sound, simply ensure that the checkboxes for Play On Awake and Loop are selected.

This will play the ambience sound clip when the player enters the scene (or level) and continually loop the clip until the scene is exited.

Your Audio Source component should look like this:

Further audio settings

As our sound is in Stereo, and therefore not affected by distance, the Min / Max Volume and Rolloff Factor settings do not apply. However, when using Mono sound, they do the following:

  • Minimum/Maximum Volume: The quietest/loudest the sound can be regardless of audio listener proximity
  • Rolloff Factor: How quickly the audio fades as the audio listener moves towards/away from the source

Step 9—Look to the skybox!

In creating 3D environments, the horizon or distance is represented by the addition of a skybox. A skybox is a cubemap—a series of six textures placed inside a cube and rendered seamlessly to appear as a surrounding sky and horizon. This cubemap sits around the 3D world at all times, and much like the actual horizon, it is not an object the player can ever get to.

To apply a skybox to your scene, go to Edit | Render Settings. The Inspector area of the interface will now change to show the preferences for the rendering of this scene. To the right of the Skybox Material setting, click on the drop-down arrow, and select Sunset. This will apply the skybox, but it is crucial to understand that any skybox you add will only be shown in the Game View panel by default.

As with many skyboxes, the Sunset skybox provided with Standard Assets features a drawn on Sun. The problem here is that we have our sun visually represented by the flare of the directional light, so we'll need to reposition the light to match the skybox. But first, we'll add our First Person Controller player character, so that you can see this issue first hand.

Step 10—Open water

As we have constructed an island terrain, it follows that our land mass should be surrounded by water. Water in Unity is created using an animated material applied to a surface. While it is possible to create further dynamic water effects by utilizing particles, the best way to add a large expanse of water is to use one of the water materials provided by Unity.

The Standard Assets package gives us two readymade surfaces with the water material applied. Readily saved as prefabs, these objects can be introduced easily from the Project Panel. Simply open the Standard Assets | Water folder.

Drag the Daylight Simple Water prefab into the scene and position it at (500, 4, 500) by filling in the X, Y and Z values for Position in the Transform component in the Inspector. In order to expand the scale of the water prefab to form a sea around the island, simply increase both the X and Z values under Scale to 1600.

This places the water in the center of the map and four meters above the sea bed. This will cover up the corners of your island, and mask the terrain's true square-based nature. It should look like this:

Step 10—Open water

Step 11—Island walkabout

In the Project panel, expand the subfolder of Standard Assets called Prefabs. In here you will find a single prefab – a readymade First Person Controller object. This can be dropped into your scene, and will allow you to walk around your terrain using the keyboard and mouse.

Drag this prefab from the Project panel onto the Scene view—remember you will not be able to accurately position this object when you initially drop it into the scene, as this should be done afterwards.

Now that your First Person Controller object is an active game object, you can see it listed in the Hierarchy and its component parts listed in the Inspector.

Reposition the First Person Controller object to (500, 35, 500) by typing the values in the Transform component in the Inspector. This position places the character directly in the centre of the map in the X and Z axes, because we have created a terrain with a width and length of 1000 meters. The Y value of 35 ensures that the player is above ground level—if it is not, then the character will fall through the map upon play. If you happen to have made a hill at this position when sculpting your terrain, simply increase the Y value to place the character above the hill at game start.

Note

To see where your character object is positioned more easily, ensure that it is selected in the Hierarchy. Then hover the mouse cursor over the Scene window and press F on the keyboard. This focuses the Scene view on the selected object.

Now press the Play button to test the game, and you should be able to walk around on your island terrain!

The default controls for the character are as follows:

  • Up/W: Walk forward
  • Down/S: Walk backward
  • Left/A: Sidestep left (also known as Strafing)
  • Right/D: Sidestep right
  • Mouse: Look around/turn the player while walking

Walk to the top of a hill and turn until you can see the flare of the Sun. Then look to the right of the flare, and you will see that the skybox also has a lit area to represent the sun, so we need to reposition the Directional Light object to correspond to the sun in the skybox, as mentioned earlier.

Stop the game testing by pressing the Play button again. It is crucial to stop the game when you continue editing. If you leave it playing or on pause, then any edits you make to the scene will only be temporary—lasting until you press Play again or quit Unity.

Step 12—Sun alignment and final tweaks

Select the Directional Light object in the Hierarchy, and in the Transform component in the Inspector, reposition the object to (-500, 500, 500). This will place the light on the side of the map which the skybox's sun is on. Rotate the object by 120 in the Y axis (center box) and your Directional light's position will now match the light in the skybox.

Finally, as we have added the First Person Controller object, we no longer need the object that our scene came with by default—Main Camera. Unity reminds us of this by showing an info message in the console preview area at the bottom of the screen:

Step 12—Sun alignment and final tweaks

To rectify this, simply remove the Main Camera object, as we no longer need it. To do this, select it in the Hierarchy, and on Mac, press Command+Backspace, on PC use Shift+Delete, or on either platform, go to Edit | Delete.

Now that this object is gone, your island terrain is complete. Save your scene so that you do not lose any work—go to File | Save Scene and name your scene Island Level—Unity will assume you want to save in the Assets folder of your project, and will choose that folder as the save location automatically because all assets must be in this folder. To keep things neat, you can make a Levels subfolder now and save in there if you like.

Congratulations, your island terrain is ready for exploration, so hit the Play button again and have a wander! Just remember to press Play again when you are finished.

Take Me Home! Introducing models

Now that our island terrain is ready for populating with gameplay, the first key concept to explore is the introduction of models from external applications. As we have provided you with models for the exercises in this book, you'll need to download and import another Unity package to add the first model asset—an outpost—to your project.

Importing the model package

Go to www.packtpub.com/files/8181_Code.zip and locate the asset package from the files available in the code bundle for this book titled Outpost.unitypackage.

Next, return to Unity and go to Assets | Import Package.

Importing the model package

Leave all files here selected, and click on the Import button to confirm. Now that you have imported the contents of the package, you'll see a new folder of assets called outpost inside your Project panel, and therefore in the Assets folder of your project in your operating system. Expand this folder by clicking on the gray arrow next to its name on the Project panel in order to view its contents.

Importing the model package

The imported folder contains the model itself and two subfolders, one with its Materials, the other containing the images that make up the Textures for those materials. You can spot a 3D model asset in Unity by its icon—a small cube icon with an accompanying page icon, differentiating it from Unity's prefab icon, which, as you'll discover, is simply a cube icon by itself.

Common settings for models

Before you introduce any model to the active scene, you should always ensure that its settings are as you require them to be in the Inspector. When Unity imports new models to your project, it is interpreting them with its FBX file format Importer.

By using the FBX Importer component in the Inspector, you can select your model file in the Project window and adjust settings for its Meshes, Materials, and Animations before your model becomes part of your game.

Meshes

In the Meshes section of FBX Importer, you can specify:

  • Scale Factor: Typically set to a value of 1, this setting states that 1 unit should equal 1 meter in the game world. If you wish your models to be scaled differently, then you can adjust them here before you add the model to the scene. However, you can always scale objects once they are in your scene using the Transform component's Scale settings.
  • Generate Colliders: This checkbox will find every individual component part of the model and assign a mesh collider to it. A mesh collider is a complex collider that can fit to complex geometric shapes and, as a result, is the usual type of collider you would expect to want to apply to all parts of a map or 3D model of a building.
  • Calculate Normals: The normal is the forward facing surface of each mesh in your 3D model, and therefore the side which is rendered as visible. By enabling this checkbox, you allow Unity to ensure that all surfaces are correctly set up to render in the game.
  • Smoothing Angle: When using the Calculate Normals function, smoothing allows you to specify how detailed an edge must be to be considered a hard edge by the game engine.
  • Split Tangents: This setting allows corrections by the engine for models imported with incorrect Bump Mapped lighting. Bump Mapping is a system of utilizing two textures, one a graphic to represent a model's appearance and the other a heightmap. By combining these two textures, the bump map method allows the rendering engine to display flat surfaces of polygons as if they have 3D deformations. When creating such effects in third-party applications and transferring to Unity, sometimes lighting can appear incorrectly, and this checkbox is designed to fix that by interpreting their materials differently.
  • Swap UVs: This setting allows the correction of import errors on lighting shaders introduced from third-party applications.

Materials

The Materials section allows you to choose how to interpret the materials created in your third-party 3D modelling application. The user can choose either Per Texture (creates a Unity material for each texture image file found) or Per Material (creates Materials only for existing materials in the original file) from the Generation drop-down menu.

Animations

The Animations section of the Importer allows you to interpret the animations created in your modelling application in a number of ways. From the Generation drop-down menu, you can choose the following methods:

  • Don't Import: Set the model to feature no animation.
  • Store in Original Roots: Set the model to feature animations on individual parent objects, as the parent or root objects may import differently in Unity.
  • Store in Nodes: Set the model to feature animations on individual child objects throughout the model, allowing more script control of the animation of each part.
  • Store in Root: Set the model to only feature animation on the parent object of the entire group.

The Animations section then features three further checkboxes:

  • Bake Animations: Tell Unity to interpret joints in models with IK (Inverse Kinematics) skeletal animation.
  • Reduce Keyframes: This removes unnecessary keyframes in exported models from modelling applications. This should always be selected as Unity does not need the keyframes and doing so will improve performance of the animated model.
  • Split Animations: When creating models to be used with Unity, animators create timeline-based animation, and by noting their frame ranges, they can add each area of animation in their timeline by specifying a name and the frames in which each animation takes place. The advantage of this is that it allows you to call individual animations by name when scripting.

Setting up the outpost model

With the outpost model you have imported and selected in the Project view, we'll use the FBX Importer component in the Inspector to adjust settings for the outpost. Ensure that:

  • Under Meshes: Scale Factor is set to 1, and Generate Colliders/Calculate Normals are selected
  • Under Materials: Generation is set to Per Texture
  • Under Animations: Reduce Keyframes and Split Animations are selected

Now using the table based area at the bottom, add three animation clips by clicking on the + (Add symbol) button to the right.

The first animation is automatically named idle, which is fine, but you'll need to specify the frame range. Therefore, under Start, place a value of 1 to tell Unity to start on frame 1, and under End, specify a value of 2.

Repeat this step to add two further animations:

  • dooropen—from frames 3 to 12
  • doorshut—from frames 13 to 24

Note

Bear in mind that these animation names are case sensitive when it comes to calling them with scripting, so ensure that you write yours literally as shown throughout this book.

The Loop field of the Animations table can be misleading for new users. It is not designed to loop the particular animation you are setting up—this is handled by the animation's Wrap Mode once it is in the scene. Instead, this feature adds a single additional frame to animations that will be looped, but the start and end frames of which do not match up in Unity after importing them from modelling applications.

FBX importeranimations sectionSetting up the outpost model

Provided that your outpost model is set up as described above, click on the Apply button to confirm these import settings, and you're all done—the model should be ready to be placed into the scene and used in our game.

主站蜘蛛池模板: 志丹县| 九龙城区| 磐安县| 永康市| 乐清市| 大荔县| 南陵县| 英山县| 龙陵县| 深泽县| 吕梁市| 修文县| 望奎县| 和硕县| 将乐县| 神农架林区| 临海市| 高碑店市| 柘荣县| 广水市| 鹿邑县| 岚皋县| 勐海县| 潼南县| 镇远县| 大足县| 冕宁县| 云阳县| 永康市| 台安县| 方山县| 宾川县| 仁寿县| 九江县| 睢宁县| 垫江县| 芷江| 柞水县| 阳新县| 社旗县| 陵川县|