Friday, January 23, 2015

Animate or Focus camera on a game object in Unity3d

Standard
Hello All:

Sometime in games we need to focus camera on an object for sometime and return to normal position. This is often called Camera Fly-By effect.. In this post, I will show how to achieve this effect in Unity3d.

By the end of tutorial, we will have our camera doing something similar to this.

We will start by creating an empty screen. Then create an empty object with following hierarchy.

Animate camera


Here "ObjectToFocus" is the target object on which our camera will be focused. We will create an empty game object, FocusPoint and will make the child of ObjectToFocus.

Animate Camera


In Scene view it will look like this
Focus Camera


To achieve animation effect we will use HOTween. HOTween is an awesome library to produce tween effects.


Now create a script "FocusCamera.cs" and copy following code in the file.

 
public GameObject targetObject;
    private Vector3 localPosition;
    void Start()
    {
        localPosition = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z);
        AnimateIt();
    }

    void AnimateIt()
    {
        StartCoroutine(FocusInAndOut());
    }

    IEnumerator FocusInAndOut()
    {
        yield return new WaitForSeconds(2.5F);
        HOTween.To(gameObject.transform, 1.5f,
new TweenParms().Prop("position", targetObject.transform.position, false).Ease(EaseType.Linear));
        yield return new WaitForSeconds(2.5F);
        HOTween.To(gameObject.transform, 1.5f, new TweenParms().Prop("position", localPosition, false).Ease(EaseType.Linear).OnComplete(StartAction));
    }
   

    private void StartAction()
    {
        Debug.Log("StartAction");
        StartCoroutine(Repeat());
    }

    IEnumerator Repeat()
    {
        yield return new WaitForSeconds(2.0f);
        AnimateIt();
    }


Attach "FocusCamera.cs" to the MainCamera in the scene and assign FocusPoint game object to TargetObject of FocusCamera script.

Animate camera

Run the scene and you will see our camera rolling. :)

Hope this helps. The full working code can be found here.

Thanks for printing this post. Hope you liked it.
Keep visiting and sharing.
Thanks,
Ashwani.

0 comments :

Post a Comment