In this recipe, we will learn how to change the camera's Depth of Field focus point to the object selected by the user.
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.
To dynamically set focus on objects using Depth of Field, perform the following steps:
CameraFocus
and open it in your editor.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; } } } } }
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.
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.
18.191.144.65