Using Cameras

Exclusive offer: get 50% off this eBook here
Unity 4.x Cookbook

Unity 4.x Cookbook — Save 50%

Over 100 recipes to spice up your Unity skills with this book and ebook.

$29.99    $15.00
by Chico Queiroz Matt Smith Zeeshan Chawdhary | August 2013 | Cookbooks Games

In this article by Matt Smith and Chico Queiroz, the authors of Unity 4.x Cookbook, we will cover:

  • Creating a picture-in-picture effect
  • Switching between multiple cameras
  • Customizing the lens flare effect
  • Making textures from screen content
  • Zooming a telescopic camera
  • Making an inspect camera
  • Creating particle effects using Shuriken
  • Displaying a mini-map

As developers, we should never forget to pay attention to the cameras. After all, they are the windows from which our players see our game. In this article, we will take a look at ways of making them more interesting within the player experience.

(For more resources related to this topic, see here.)

Creating a picture-in-picture effect

Having more than one viewport displayed can be useful in many situations. For example, you might want to show simultaneous events going on in different locations, or maybe you want to have a separate window for hot-seat multiplayer games. Although you could do it manually by adjusting the Normalized Viewport Rect parameters on your camera, this recipe includes a series of extra preferences to make it more independent from the user's display configuration.

Getting ready

For this recipe, we have prepared a package named basicLevel containing a scene. The package is in the 0423_02_01_02 folder.

How to do it...

To create a picture-in-picture display, just follow these steps:

  1. Import the basicLevel package into your Unity project.
  2. In the Project view, open basicScene, inside the folder 02_01_02. This is a basic scene featuring a directional light, a camera, and some geometry.
  3. Add the Camera option to the scene through the Create dropdown menu on top of the Hierarchy view, as shown in the following screenshot:

  4. Select the camera you have created and, in the Inspector view, set its Depth to 1:

  5. In the Project view, create a new C# script and rename it PictureInPicture.
  6. Open your script and replace everything with the following code:

    using UnityEngine;
    public class PictureInPicture: MonoBehaviour {
    public enum HorizontalAlignment{left, center, right};
    public enum VerticalAlignment{top, middle, bottom};
    public HorizontalAlignment horizontalAlignment =
    HorizontalAlignment.left;
    public VerticalAlignment verticalAlignment =
    VerticalAlignment.top;
    public enum ScreenDimensions{pixels, screen_percentage};
    public ScreenDimensions dimensionsIn = ScreenDimensions.
    pixels;
    public int width = 50;
    public int height= 50;
    public float xOffset = 0f;
    public float yOffset = 0f;
    public bool update = true;
    private int hsize, vsize, hloc, vloc;
    void Start (){
    AdjustCamera ();
    }
    void Update (){
    if(update)
    AdjustCamera ();
    }
    void AdjustCamera(){
    if(dimensionsIn == ScreenDimensions.screen_percentage){
    hsize = Mathf.RoundToInt(width * 0.01f * Screen.
    width);
    vsize = Mathf.RoundToInt(height * 0.01f * Screen.
    height);
    } else {
    hsize = width;
    vsize = height;
    }
    if(horizontalAlignment == HorizontalAlignment.left){
    hloc = Mathf.RoundToInt(xOffset * 0.01f *
    Screen.width);
    } else if(horizontalAlignment == HorizontalAlignment.
    right){
    hloc = Mathf.RoundToInt((Screen.width - hsize)
    - (xOffset * 0.01f * Screen.width));
    } else {
    hloc = Mathf.RoundToInt(((Screen.width * 0.5f)
    - (hsize * 0.5f)) - (xOffset * 0.01f * Screen.height));
    }
    if(verticalAlignment == VerticalAlignment.top){
    vloc = Mathf.RoundToInt((Screen.height -
    vsize) - (yOffset * 0.01f * Screen.height));
    } else if(verticalAlignment == VerticalAlignment.
    bottom){
    vloc = Mathf.RoundToInt(yOffset * 0.01f *
    Screen.height);
    } else {
    vloc = Mathf.RoundToInt(((Screen.height *
    0.5f) - (vsize * 0.5f)) - (yOffset * 0.01f * Screen.height));
    }
    camera.pixelRect = new Rect(hloc,vloc,hsize,vsize);
    }
    }

  7. In case you haven't noticed, we are not achieving percentage by dividing numbers by 100, but rather multiplying them by 0.01. The reason behind that is performance: computer processors are faster multiplying than dividing.

  8. Save your script and attach it to the new camera that you created previously.
  9. Uncheck the new camera's Audio Listener component and change some of the PictureInPicture parameters: change Horizontal Alignment to Right, Vertical Alignment to Top, and Dimensions In to pixels. Leave XOffset and YOffset as 0, change Width to 400 and Height to 200, as shown below:

  10. Play your scene. The new camera's viewport should be visible on the top right of the screen:

How it works...

Our script changes the camera's Normalized Viewport Rect parameters, thus resizing and positioning the viewport according to the user preferences.

There's more...

The following are some aspects of your picture-in-picture you could change.

Making the picture-in-picture proportional to the screen's size
If you change the Dimensions In option to screen_percentage, the viewport size will be based on the actual screen's dimensions instead of pixels.

Changing the position of the picture-in-picture
Vertical Alignment and Horizontal Alignment can be used to change the viewport's origin. Use them to place it where you wish.

Preventing the picture-in-picture from updating on every frame
Leave the Update option unchecked if you don't plan to change the viewport position in running mode. Also, it's a good idea to leave it checked when testing and then uncheck it once the position has been decided and set up.

See also

  • The Displaying a mini-map recipe.

Switching between multiple cameras

Choosing from a variety of cameras is a common feature in many genres: race sims, sports sims, tycoon/strategy, and many others. In this recipe, we will learn how to give players the ability of choosing an option from many cameras using their keyboard.

Getting ready

In order to follow this recipe, we have prepared a package containing a basic level named basicScene. The package is in the folder 0423_02_01_02.

How to do it...

To implement switchable cameras, follow these steps:

  1. Import the basicLevel package into your Unity project.
  2. In the Project view, open basicScene from the 02_01_02 folder. This is a basic scene featuring a directional light, a camera, and some geometry.
  3. Add two more cameras to the scene. You can do it through the Create drop-down menu on top of the Hierarchy view. Rename them cam1 and cam2.
  4. Change the cam2 camera's position and rotation so it won't be identical to cam1.
  5. Create an Empty game object by navigating to Game Object | Create Empty. Then, rename it Switchboard.
  6. In the Inspector view, disable the Camera and Audio Listener components of both cam1 and cam2.

  7. In the Project view, create a new C# script. Rename it CameraSwitch and open it in your editor.
  8. Open your script and replace everything with the following code:

    using UnityEngine;
    public class CameraSwitch : MonoBehaviour {
    public GameObject[] cameras;
    public string[] shortcuts;
    public bool changeAudioListener = true;
    void Update (){
    int i = 0;
    for(i=0; i<cameras.Length; i++){
    if (Input.GetKeyUp(shortcuts[i]))
    SwitchCamera(i);
    }
    }
    void SwitchCamera ( int index ){
    int i = 0;
    for(i=0; i<cameras.Length; i++){
    if(i != index){
    if(changeAudioListener){
    cameras[i].
    GetComponent<AudioListener>().enabled = false;
    }
    cameras[i].camera.enabled = false;
    } else {
    if(changeAudioListener){
    cameras[i].
    GetComponent<AudioListener>().enabled = true;
    }
    cameras[i].camera.enabled = true;
    }
    }
    }
    }

  9. Attach CameraSwitch to the Switchboard game object.
  10. In the Inspector view, set both Cameras and Shortcuts size to 3. Then, drag the scene cameras into the Cameras slots, and type 1, 2, and 3 into the Shortcuts text fields, as shown in the next screenshot.

  11. Play your scene and test your cameras.

How it works...

The script is very straightforward. All it does is capture the key pressed and enable its respective camera (and its Audio Listener, in case the Change Audio Listener option is checked).

There's more...

Here are some ideas on how you could try twisting this recipe a bit.

Using a single-enabled camera

A different approach to the problem would be keeping all the secondary cameras disabled and assigning their position and rotation to the main camera via a script (you would need to make a copy of the main camera and add it to the list, in case you wanted to save its transform settings).

Triggering the switch from other events

Also, you could change your camera from other game object's scripts by using a line of code, such as the one shown here:

GameObject.Find("Switchboard").GetComponent("CameraSwitch").
SwitchCamera(1);

See also

  • The Making an inspect camera recipe.

Customizing the lens flare effect

As anyone who has played a game set in an outdoor environment in the last 15 years can tell you, the lens flare effect is used to simulate the incidence of bright lights over the player's field of view. Although it has become a bit overused, it is still very much present in all kinds of games. In this recipe, we will create and test our own lens flare texture.

Getting ready

In order to continue with this recipe, it's strongly recommended that you have access to image editor software such as Adobe Photoshop or GIMP. The source for lens texture created in this recipe can be found in the 0423_02_03 folder.

How to do it...

To create a new lens flare texture and apply it to the scene, follow these steps:

  1. Import Unity's Character Controller package by navigating to Assets | Import Package | Character Controller.
  2. Do the same for the Light Flares package.
  3. In the Hierarchy view, use the Create button to add a Directional Light effect to your scene.
  4. Select your camera and add a Mouse Look component by accessing the Component | Camera Control | Mouse Look menu option.
  5. In the Project view, locate the Sun flare (inside Standard Assets | Light Flares), duplicate it and rename it to MySun, as shown in the following screenshot:

  6. In the Inspector view, click Flare Texture to reveal the base texture's location in the Project view. It should be a texture named 50mmflare.
  7. Duplicate the texture and rename it My50mmflare.

  8. Right-click My50mmflare and choose Open. This should open the file (actually a.psd) in your image editor. If you're using Adobe Photoshop, you might see the guidelines for the texture, as shown here:

  9. To create the light rings, create new Circle shapes and add different Layer Effects such as Gradient Overlay, Stroke, Inner Glow, and Outer Glow.
  10. Recreate the star-shaped flares by editing the originals or by drawing lines and blurring them.

  11. Save the file and go back to the Unity Editor.
  12. In the Inspector view, select MySun, and set Flare Texture to My50mmflare:

  13. Select Directional Light and, in the Inspector view, set Flare to MySun.

  14. Play the scene and move your mouse around. You will be able to see the lens flare as the camera faces the light.

How it works...

We have used Unity's built-in lens flare texture as a blueprint for our own. Once applied, the lens flare texture will be displayed when the player looks into the approximate direction of the light.

There's more...

Flare textures can use different layouts and parameters for each element. In case you want to learn more about the Lens Flare effect, check out Unity's documentation at http://docs. unity3d.com/Documentation/Components/class-LensFlare.html.

Making textures from screen content

If you want your game or player to take in-game snapshots and apply it as a texture, this recipe will show you how. This can be very useful if you plan to implement an in-game photo gallery or display a snapshot of a past key moment at the end of a level (Race Games and Stunt Sims use this feature a lot).

Getting ready

In order to follow this recipe, please import the basicTerrain package, available in the 0423_02_04_05 folder, into your project. The package includes a basic terrain and a camera that can be rotated via a mouse.

How to do it...

To create textures from screen content, follow these steps:

  1. Import the Unity package and open the 02_04_05 scene.
  2. We need to create a script. In the Project view, click on the Create drop-down menu and choose C# Script. Rename it ScreenTexture and open it in your editor.
  3. Open your script and replace everything with the following code:

    using UnityEngine;
    using System.Collections;
    public class ScreenTexture : MonoBehaviour {
    public int photoWidth = 50;
    public int photoHeight = 50;
    public int thumbProportion = 25;
    public Color borderColor = Color.white;
    public int borderWidth = 2;
    private Texture2D texture;
    private Texture2D border;
    private int screenWidth;
    private int screenHeight;
    private int frameWidth;
    private int frameHeight;
    private bool shoot = false;
    void Start (){
    screenWidth = Screen.width;
    screenHeight = Screen.height;
    frameWidth = Mathf.RoundToInt(screenWidth * photoWidth *
    0.01f);
    frameHeight = Mathf.RoundToInt(screenHeight * photoHeight
    * 0.01f);
    texture = new Texture2D (frameWidth,frameHeight,TextureFor
    mat.RGB24,false);
    border = new Texture2D (1,1,TextureFormat.ARGB32, false);
    border.SetPixel(0,0,borderColor);
    border.Apply();
    }
    void Update (){
    if (Input.GetKeyUp(KeyCode.Mouse0))
    StartCoroutine(CaptureScreen());
    }
    void OnGUI (){
    GUI.DrawTexture(new Rect((screenWidth*0.5f)-
    (frameWidth*0.5f) - borderWidth*2,((screenHeight*0.5f)-
    (frameHeight*0.5f)) - borderWidth,frameWidth + borderWidth*2,borde
    rWidth),border,ScaleMode.StretchToFill);
    GUI.DrawTexture(new Rect((screenWidth*0.5f)-
    (frameWidth*0.5f) - borderWidth*2,(screenHeight*0.5f)+(frameHeigh
    t*0.5f),frameWidth + borderWidth*2,borderWidth),border,ScaleMode.
    StretchToFill);
    GUI.DrawTexture(new Rect((screenWidth*0.5f)-
    (frameWidth*0.5f)- borderWidth*2,(screenHeight*0.5f)-(frameHeight*
    0.5f),borderWidth,frameHeight),border,ScaleMode.StretchToFill);
    GUI.DrawTexture(new Rect((screenWidth*0.5f)+(frameWidth*0.
    5f),(screenHeight*0.5f)-(frameHeight*0.5f),borderWidth,frameHeight
    ),border,ScaleMode.StretchToFill);
    if(shoot){
    GUI.DrawTexture(new Rect (10,10,frameWidth*thumbPropo
    rtion*0.01f,frameHeight*thumbProportion* 0.01f),texture,ScaleMode.
    StretchToFill);
    }
    }
    IEnumerator CaptureScreen (){
    yield return new WaitForEndOfFrame();
    texture.ReadPixels(new Rect((screenWidth*0.5f)-(frameWidth
    *0.5f),(screenHeight*0.5f)-(frameHeight*0.5f),frameWidth,frameHeig
    ht),0,0);
    texture.Apply();
    shoot = true;
    }
    }

  4. Save your script and apply it to the Main Camera game object.
  5. In the Inspector view, change the values for the Screen Capturecomponent, leaving Photo Width and Photo Height as 25 and Thumb Proportion as 75, as shown here:

  6. Play the scene. You will be able to take a snapshot of the screen (and have it displayed on the top-left corner) by clicking the mouse button.

How it works...

Clicking the mouse triggers a function that reads pixels within the specified rectangle and applies them into a texture that is drawn by the GUI.

There's more...

Apart from displaying the texture as a GUI element, you could use it in other ways.

Applying your texture to a material
You apply your texture to an existing object's material by adding a line similar to
GameObject.Find("MyObject").renderer.material.mainTexture = texture;
at the end of the CaptureScreen function.

Using your texture as a screenshot
You can encode your texture as a PNG image file and save it. Check out Unity's documentation on this feature at http://docs.unity3d.com/Documentation/ScriptReference/ Texture2D.EncodeToPNG.html.

Unity 4.x Cookbook Over 100 recipes to spice up your Unity skills with this book and ebook.
Published: June 2013
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

Zooming a telescopic camera

In this recipe, we will create a telescopic camera that zooms in whenever the left mouse button is pressed. This can be very useful, for instance, if we have a sniper in our game.

Getting ready

In order to follow this recipe, please import the basicTerrain package, available in the 0423_02_04_05 folder, into your project. The package includes a basic terrain and a camera that can be rotated via a mouse.

How to do it...

To create a telescopic camera, follow these steps:

  1. Import the Unity package and open the 02_04_05 scene.
  2. We need to create a script. In the Project view, click on the Create drop-down menu and choose C# Script. Rename it TelescopicView and open it in your editor.
  3. Open your script and replace everything with the following code:

    using UnityEngine;
    using System.Collections;
    public class TelescopicView : MonoBehaviour{
    public float ZoomLevel = 2.0f;
    public float ZoomInSpeed = 100.0f;
    public float ZoomOutSpeed = 100.0f;
    private float initFOV;
    //private Vignetting vignette;
    //public float vignetteAmount = 10.0f;
    void Start(){
    initFOV = Camera.main.fieldOfView;
    //vignette = this.GetComponent("Vignetting") as
    Vignetting;
    }
    void Update(){
    if (Input.GetKey(KeyCode.Mouse0)){
    ZoomView();
    }else{
    ZoomOut();
    }
    }
    void ZoomView(){
    if (Mathf.Abs(Camera.main.fieldOfView - (initFOV /
    ZoomLevel)) < 0.5f){
    Camera.main.fieldOfView = initFOV / ZoomLevel;
    // vignette. intensity = vignetteAmount;
    }else if (Camera.main.fieldOfView - (Time.deltaTime *
    ZoomInSpeed) >= (initFOV / ZoomLevel)){
    Camera.main.fieldOfView -= (Time.deltaTime *
    ZoomInSpeed);
    // vignette. intensity = vignetteAmount * (Camera.main.
    fieldOfView - initFOV)/((initFOV / ZoomLevel) - initFOV);
    }
    }
    void ZoomOut(){
    if (Mathf.Abs(Camera.main.fieldOfView - initFOV) < 0.5f){
    Camera.main.fieldOfView = initFOV;
    // vignette. intensity = 0;
    }else if (Camera.main.fieldOfView + (Time.deltaTime *
    ZoomOutSpeed) <= initFOV){
    Camera.main.fieldOfView += (Time.deltaTime *
    ZoomOutSpeed);
    //vignette.intensity = vignetteAmount * (Camera.main.
    fieldOfView - initFOV)/((initFOV / ZoomLevel) - initFOV);
    }
    }
    }

  4. Save your script and apply it to the Main Camera game object.
  5. Play your scene. You should be able to zoom in the camera view by clicking the mouse button and zoom out by releasing it.
  6. The next steps are for only those using Unity Pro. If you are using Unity Pro, please stop the scene.
  7. Import Unity's Image Effects package by navigating to Assets | Import Package | Image Effects (Pro Only).
  8. Select the Main Camera option and apply the Vignette image effect (by navigating to Component | Image Effects | Vignette).
  9. Open the TelescopicView script and uncomment every commented line (these are the ones referencing the vignetteAmount variable).
  10. Save the script and play the level. You should see an animated vignetting effect in addition to the zooming:

How it works...

The zooming effect is actually caused by the increment made by the script on the value of the camera's Field of View property, while the mouse button is pressed.

There's more...

If you are using Unity Pro, you could also add a variable to control the Blur Vignette level of the Vignette image effect.

Making an inspect camera

Inspect cameras are a very popular way of displaying products online. These virtual displays usually feature a camera that orbits around and zooms in and out the product. In this recipe, we will learn how to implement such a camera using a standard Unity component as a starting point.

Getting ready

In order to follow this recipe, please import the inspectScene package, available in the 0423_02_06 folder, into your project. The package includes a basic scene containing the 3D model of a mobile phone and a camera.

Please note this recipe involves editing a JavaScript file provided by Unity. In case you want the C# version of the final script, we have included it in the 0423_02_06 folder.

How to do it...

To create an inspect camera, follow these steps:

  1. Import the inspectScene Unity package and open the scene available in the 02_06 folder, also named inspectScene.
  2. Add a directional light to the scene, making it cast light in the same direction the camera is facing.
  3. In the Hierarchy view, drag the Directional Light into the Main Camera game object, making it a child of the Main Camera game object.
  4. Make sure the MouseOrbit script is available at the Project view (it should be inside the Standard Assets | Scripts | Camera Scripts folder). If not, import the Scripts package by navigating to Assets | Import Package | Scripts.
  5. Duplicate the MouseOrbit script and rename the new copy to InspectCamera.
  6. Open the InspectCamera script in your editor.
  7. Insert, before the line starting with @script, insert the following code:

    var zoomInLimit = 2.0;
    var zoomOutLimit = 1.0;
    private var initialFOV : float;

  8. Then, change the line starting with @script to:

    @script AddComponentMenu("Camera-Control/Inspect Camera")

  9. Also, add the following lines of code right after the Start function begins:

    initialFOV = camera.fieldOfView;
    transform.position = new Vector3(0.0f, 0.0f, -distance) + target. position;

  10. Then, replace all of the LateUpdate function with the following code:

    function LateUpdate () {
    if (target && Input.GetMouseButton(0)) {
    if(Input.GetKey(KeyCode.RightShift) || Input. GetKey(KeyCode.LeftShift)){
    var zoom = camera.fieldOfView - Input.GetAxis

    ("Mouse Y");


    if(zoom >= initialFOV / zoomInLimit && zoom <=

    initialFOV / zoomOutLimit){
    camera.fieldOfView -= Input.GetAxis

    ("Mouse Y");


    }
    } else {
    x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
    y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
    }

    y = ClampAngle(y, yMinLimit, yMaxLimit);
    var rotation = Quaternion.Euler(y, x, 0);
    var position = rotation * Vector3(0.0, 0.0, -distance) +
    target.position;
    transform.rotation = rotation;
    transform.position = position;
    }
    }

  11. Save the script. Then, select the Main Camera option in the Hierarchy view and add the Inspect Camera component by navigating to Component | Camera-Control | Inspect Camera, as shown in the following screenshot:

  12. The Inspect Camera component should now be available in the Inspector window for the Main Camera. From the Hierarchy view, drag the mobile game object into the Target slot. Then, change the Distance value to 1:

  13. Play the scene. Move the mouse and keep the left button pressed to look around the object. To zoom in and out, keep the left button and the Shift key pressed, and move the mouse vertically.

How it works...

Unlike Unity's MouseOrbit, our InspectCamera script checks if the mouse button is pressed as a condition to move the camera. We have also implemented a zooming feature that changes the value of the camera's Field of View when the Shift key and a mouse button are pressed, and the mouse is moved vertically.

There's more...

If you want a C# version of the script, don't worry; we have included it in the 0423_02_07 folder. Also, should you need to use another key instead of Shift, check out Unity's documentation for the appropriate key codes at http://docs.unity3d.com/ Documentation/ScriptReference/KeyCode.html.

Creating particle effects using Shuriken

From Unity 3.5 onwards, much more impressive effects can be created using particle systems. Many effects which used to need scripting can be achieved entirely through the Shuriken particle system settings.

Getting ready

It is useful to review important properties and the parameter value selection methods of Unity particle systems before actually trying to work with them in the editor itself.

Some of the fundamental properties of particle systems include the following:

  • Energy: How long a particle will "live" until it is destroyed
  • Looping: Whether the entire population of particles will be recreated again once the last particle has "died"
  • Speed, direction, and rotation: Each particle has its own transform, and when a new particle is created the particle system determines (from the settings you have chosen) that particle's direction and speed of movement and any rotation

In addition, it is important to understand the different methods that values are chosen for particle properties:

  • Constant: The same value for all of the particles
  • Curve: How the values will change over the duration of each cycle of the particle system (for example, particles start small and get larger over time)
  • Random number between maximum and minimum constants: Values are randomly chosen from the same range over each cycle of the particle system
  • Random number between two curves: This allows the range of values from which values are chosen to change over the duration of each cycle of the particle system

The following screenshot shows two particle-size curves, that ensures particles start small (between 0.0 and 0.2), and get larger over the 3 second (x-axis) cycle length. However, the size of particles is random between the two curves (a value always chosen in the "red" zone), so towards the end of the cycle, particles will be a random size between 1.0 and 2.8:

How to do it...

To create a particle effects using Shuriken, follow these steps:

  1. Create a new Unity project and import the Particles Unity package.
  2. Create a new particle system.
  3. Reset the particle system to its defaults by choosing Reset from the component's Context menu in the Inspector.

    To view the Context menu, either right-click on the component's name, or click the tiny gear icon at the top-right corner of the component's section in the Inspector view, as shown here:

  4. Switch on (check) Wireframe for the Render section of the particle system, shown below:

    Wireframes can aid in understanding the position and movement of particles by drawing a blue bounding rectangle around each particle in the Scene window, and a white bounding rectangle around the complete set of particles of each frame.

  5. Display the Renderer properties (double-click the darker grey title bar) and change the renderer's Material parameter to SoapBubble:

    You'll find materials from the Unity particles package located in the Project folder as follows: Standard Assets | Particles |Sources | Materials.

  6. Set Start Speed to 2 and set Start Size to a random number between the constants 0.2 and 1:

How it works...

You've created a particle system which emits differently-sized rising particles showing a soap bubble. They move relatively slowly (since you set Start Speed to 2). Each particle shows a soap bubble, since you set the renderer to use a material that had a soap bubble texture image. The bubbles vary in size since you set Start Size to be a random number between 0.2 and 1. They float upwards because the system is rotated by -90 on the X-axis (the default settings you ensured by clicking Reset).

There's more...

Here is some information on how to fine-tune and customize this recipe.

Scrubbing back and forward through the particle animation
A nice feature to easily review and ensure that the particle system's behavior is as desired is the ability to "scrub" (move back and forward through the animation). This is achieved by clicking and dragging left or right on Playback Time text in the particle Preview Panel in the Scene window:

Learning more from the Unity documentation
Unity particle systems with Shuriken can be very powerful and therefore complex components of games. The Unity manual provides several pages dedicated to introducing and describing this system. You'll find the ParticleSystems.html file in the /Documentation/Manual/ section of the Unity website, and also in your own computer's Unity application folder.

Adding effects through Particle Effect
Opening the Window | Particle Effect menu and clicking the plus symbol adds additional particle sub-systems. Complex effects can be created through particle systems working at different times with different settings.

Displaying a mini-map

In many games, a broader view of the scene can be invaluable for navigation and information. Mini-maps are great for giving players that extra perspective they might need when in first- or third-person mode.

Getting ready

In order to follow this recipe, please import the miniMap package, available in the 0423_02_08 folder, into your project. The package includes a scene containing a third-person controller inside a simple maze, and also a texture named marker.

How to do it...

To create a mini-map, follow these steps:

  1. Import the miniMap Unity package and open the scene named thirdPerson, available in the 02_08 folder.
  2. Select the 3rd Person Controller option and, in the Inspector view, add it to a new layer named NoMap:

  3. Create a new camera. Rename it Map Camera and, in the Inspector view, change its parameters as follows:
    • Clear Flags: Depth Only
    • Culling Mask: Mixed…(unselect NoMap)
    • Projection: Orthographic
    • Depth: 1(also, uncheck the camera's Audio Listener component)

  4. In the Project window, create a new C# Script and name it GenerateMap. Open it and replace everything with the following code:

    using UnityEngine;
    using System.Collections;
    public class GenerateMap : MonoBehaviour
    {
    public Transform target;
    public Texture2D marker;
    public float camHeight = 1.0f;
    public bool freezeRotation = true;
    public float camDistance = 2.0f;
    public enum ha {left, center, right};
    public enum va {top, middle, bottom};
    public ha horizontalAlignment = ha.left;
    public va verticalAlignment = va.top;
    public enum sd {pixels, screen_percentage};
    public sd dimensionsIn = sd.pixels;
    public int width = 50;
    public int heigth = 50;
    public float xOffset = 0f;
    public float yOffset = 0f;
    void Start(){
    Vector3 angles = transform.eulerAngles;
    angles.x = 90;
    angles.y = target.transform.eulerAngles.y;
    transform.eulerAngles = angles;
    Draw();
    }
    void Update(){
    transform.position = new Vector3(target.transform.
    position.x, target.transform.position.y + camHeight, target.
    transform.position.z);
    camera.orthographicSize = camDistance;
    if (freezeRotation){
    Vector3 angles = transform.eulerAngles;
    angles.y = target.transform.eulerAngles.y;
    transform.eulerAngles = angles;
    }
    }
    void Draw() {
    int hsize = Mathf.RoundToInt(width * 0.01f * Screen.
    width);
    int vsize = Mathf.RoundToInt(heigth * 0.01f * Screen.
    height);
    int hloc = Mathf.RoundToInt(xOffset * 0.01f * Screen.
    width);;
    int vloc = Mathf.RoundToInt((Screen.height - vsize) -
    (yOffset * 0.01f * Screen.height));
    if(dimensionsIn == sd.screen_percentage){
    hsize = Mathf.RoundToInt(width * 0.01f * Screen.
    width);
    vsize = Mathf.RoundToInt(heigth * 0.01f * Screen.
    height);
    } else {
    hsize = width;
    vsize = heigth;
    }
    switch(horizontalAlignment){
    case ha.left:
    hloc = Mathf.RoundToInt(xOffset * 0.01f *
    Screen.width);
    break;
    case ha.right:
    hloc = Mathf.RoundToInt((Screen.width -
    hsize) - (xOffset * 0.01f * Screen.width));
    break;
    case ha.center:
    hloc = Mathf.RoundToInt(((Screen.width *
    0.5f) - (hsize * 0.5f)) - (xOffset * 0.01f * Screen.height));
    break;
    }
    switch(verticalAlignment){
    case va.top:
    vloc = Mathf.RoundToInt((Screen.height -
    vsize) - (yOffset * 0.01f * Screen.height));
    break;
    case va.bottom:
    vloc = Mathf.RoundToInt(yOffset * 0.01f *
    Screen.height);
    break;
    case va.middle:
    vloc = Mathf.RoundToInt(((Screen.height *
    0.5f) - (vsize * 0.5f)) - (yOffset * 0.01f * Screen.height));
    break;
    }
    camera.pixelRect = new Rect(hloc,vloc,hsize,vsize);
    }
    void OnGUI(){
    Vector3 markerPos = camera. camera.WorldToViewportPoint
    (target.position);
    int pointX = Mathf.RoundToInt((camera.pixelRect.xMin +
    camera.pixelRect.xMax) * markerPos.x);
    int pointY = Mathf.RoundToInt(Screen.height - (camera.
    pixelRect.yMin + camera.pixelRect.yMax) * markerPos.y);
    GUI.DrawTexture( new Rect(pointX-(marker.width *
    0.5f),pointY-(marker.height * 0.5f),marker.width,marker.height),
    marker, ScaleMode.StretchToFill, true, 10.0f);
    }
    }

  5. Save the script and attach it to the Map Camera. Then, in the Inspector view, change parameters of the Generate Map component as follows:
    • Target: 3rd Person Controller
    • Marker: marker
    • Cam Height: 6
    • Cam Distance: 10
    • Horizontal Alignment: Right
    • Vertical Alignment: Bottom
    • Dimensions In: screen_percentage
    • XOffset and YOffset: 0
    • Width: 25
    • Height: 25

  6. Play the scene. You should be able to see the mini-map functioning in the bottom-right corner of the screen:

How it works...

Our script performs two main actions: it sets up the viewport according to the desired position and dimensions, and also adjusts the camera's transform settings, making it follow the main character from a top-view perspective. Plus, in order to make the map look cleaner, it hides our main character while displaying a marker where he should be.

There's more...

If you want to experiment more with your mini-map, read on.

Using Render Texture (Pro only)
If you use Unity Pro, you could always use Render Texture and display your map using GUI. DrawTexture or Graphics.DrawTexture. For more information on Render Texture, please check the Unity documentation at http://docs.unity3d.com/Documentation/ Components/class-RenderTexture.html.

Adapting your mini-map to other styles
You could easily modify this recipe to make a top or isometric view of a racing game circuit map. Just position the camera manually and prevent it from following the character. Also, don't forget to add markers for all the vehicles!

Summary

This article explained techniques for controlling and enhancing your game's camera. This article also presented interesting solutions to work with both single and multiple cameras.

Resources for Article :


Further resources on this subject:


Unity 4.x Cookbook Over 100 recipes to spice up your Unity skills with this book and ebook.
Published: June 2013
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

About the Author :


Chico Queiroz

Chico Queiroz is a multimedia designer from Rio de Janeiro, Brazil. Chico initiated his career back in 2000, soon after graduating in Communications/Advertising (PUC-Rio), working with advergames and webgames using Flash and Director at LocZ Multimedia. Here he contributed to the design and development of games for clients, such as Volkswagen and Parmalat, along with some independent titles.

Chico has a Master's Degree in Digital Game Design (University for the Creative Arts, UK). His final project was exhibited at events and festivals, such as London Serious Games Showcase and FILE. Chico has also published articles for academic conferences and websites, such as gameology.org, gamasutra.com, and gamecareerguide.com.

He curated and organized an exhibition, held at SBGames 2009, which explored connections between video games and art. SBGames is the annual symposium of the Special Commission of Games and Digital Entertainment of the Computing Brazilian Society.

Chico currently works as a Digital Designer at the Computer Graphics Technology Group (TecGraf), within the Pontifical Catholic University of Rio de Janeiro (PUC-Rio), where he, among other responsibilities, uses Unity to develop interactive presentations and concept prototypes for interactive visualization software. He also works as a lecturer at PUC-Rio, teaching undergraduate Design students 3D modeling and Technology/CG for Games, in which Unity is used as the engine for the students' projects.

Matt Smith

Matt Smith is senior lecturer in computing at the Institute of Technology Blanchardstown, Dublin, Ireland (www.itb.ie). In 1980 (you do the math) Matt started computer programming (on a ZX80) and has been programming ever since. In 1985, Matt wrote the lyrics, and was a member of the band that played (and sang, sorry about that by the way) the music on the B-side of the audio cassette carrying the computer game Confuzion (wikipedia.org/wiki/Confuzion).

Matt holds a bachelor's degree in Business Computing (Huddersfield University, UK), and as that was a bit boring, he went on to get a masters in Artificial Intelligence (Aberdeen University, Scotland), and a PhD in Computational Musicology (Open University, UK). Having run out of money after 10 years as a full-time student, he began his career as a lecturer and academic. He has been lecturing and researching on programming, artificial intelligence, web development, and interactive multimedia for almost 20 years, holding full-time positions at Winchester University and London's Middlesex University, before moving to his present post in Ireland in 2002. In recent years, Matt has replaced Flash-based 2D multimedia with Unity-based 3D game development and interactive virtual environments subjects for his computing and digital media undergraduates.

To keep himself fit, Matt took up the Korean martial art of Taekwon-Do (he developed and runs his club's website at www.maynoothtkd.com), and a group of his BSc students are now developing a Unity-based Taekwon-Do interactive "tutor" with Microsoft Kinect cameras. Some of his previous Irish-French student team games can be found and played at www.saintgermes.com (thanks for continuing to host these, Guillem!). Matt was one of the two technical experts for a recent multimedia European project for language and cultural student work mobility (vocalproject.eu).

Matt is currently struggling to learn Korean (for his Taekwon-Do), and Irish (since his daughter Charlotte attends an Irish-speaking school and he doesn't believe her translations of her teacher's report cards ...). In 2012, he started taking classical piano lessons again (after a
20-year gap), with a view to sitting exams starting May, 2013.

Matt's previous authoring includes contributions to Serious Games and Edutainment Applications, Springer (2011), Musical Imagery, Routledge (2001). He was also lead editor for Music Education: An Artificial Intelligence Approach, Springer (1994), and a technical reviewer for Internet and World Wide Web: How to Program (3rd Edition) by Deitel, Deitel & Goldberg, Prentice Hall (2003).

Books From Packt


Unity 3.x Scripting
Unity 3.x Scripting

Unity Game Development Essentials
Unity Game Development Essentials

Unity 3.x Game Development Essentials
Unity 3.x Game Development Essentials

Unity iOS Game Development Beginners Guide
Unity iOS Game Development Beginners Guide

Unity 3 Game Development Hotshot
Unity 3 Game Development Hotshot

Unity iOS Essentials
Unity iOS Essentials

Unity Shaders and Effects Cookbook
Unity Shaders and Effects Cookbook

Unity 3.x Game Development by Example Beginner's Guide
Unity 3.x Game Development by Example Beginner's Guide


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
k
5
z
b
d
d
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software