Dynamically focusing objects with Depth of Field

In this recipe, we will learn how to change the camera's Depth of Field focus point to the object selected by the user.

Getting ready

In order to follow this recipe, please import the ObjectFocus package, available in the 0423_11_01 folder, into your project. The package includes a basic scene containing a Go board game setup and a camera.

How to do it...

To dynamically set focus on objects using Depth of Field, perform the following steps:

  1. Import the ObjectFocus package and open the goBoardGame scene, inside the 11_01 folder. Also import, if you haven't done so already, the Package Image Effects (Assets | Import Package | Image Effects (Pro Only)).
  2. Select the Main Camera and apply the Depth of Field 3.4 image effect (Component | Image Effects | Depth of Field (3.4)).
  3. With the Main Camera selected, access the Depth of Field component in the Inspector window and apply the boardGo game object as the Object Focus target. Also, change Focal Distance to 1:
    How to do it...
  4. In the Project view, click on the Create drop-down menu and choose C# Script. Rename it to CameraFocus and open it in your editor.
  5. Open your script and replace everything with the following code:
    using UnityEngine;
    using System.Collections;
    
    public class CameraFocus : MonoBehaviour
    {
      private DepthOfField34 depthOfField;
    
      void Start(){
        depthOfField = GetComponent<DepthOfField34>();
      }
        void Update(){     
            if (Input.GetButtonDown ("Fire1")) { 
            Ray ray= Camera.main.ScreenPointToRay (Input.mousePosition); 
                RaycastHit hit ; 
            if(depthOfField){
                if (Physics.Raycast(ray, out hit, Camera.main.farClipPlane)) { 
                      depthOfField.objectFocus = hit.collider.transform; 
                  } 
              }
            }
        }
    }
  6. Save your script and attach it to Main Camera.
  7. Play your scene. You should be able focus on individual tokens by clicking on them.

How it works...

The CameraFocus script uses a Raycast() function to check for collidrs and, if positive, designates the collider's game object as the new focal point for the Depth of Field 3.4 effect. Thus, it is important that these objects have colliders attached to them.

There's more...

Unity 4 includes a new, improved Depth of Field (Lens Blur, Scatter, and DX11). To use it instead of Version 3.4, please see the script named CameraFocusScatter in the 0423_11_01 folder.

See also

  • The Zooming a telescopic camera recipe in Chapter 2, Using Cameras
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.237.79