Camera setup

Checked with version: 4.6

-

Difficulty: Beginner

This is part 3 of 10 of the Survival Shooter tutorial, in which you will design the camera view and behaviour.

Camera setup

Beginner Survival Shooter tutorial

Transcripts

CameraFollow

Code snippet

using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour
{
    public Transform target;            // The position that that camera will be following.
    public float smoothing = 5f;        // The speed with which the camera will be following.

    Vector3 offset;                     // The initial offset from the target.

    void Start ()
    {
        // Calculate the initial offset.
        offset = transform.position - target.position;
    }

    void FixedUpdate ()
    {
        // Create a postion the camera is aiming for based on the offset from the target.
        Vector3 targetCamPos = target.position + offset;

        // Smoothly interpolate between the camera's current position and it's target position.
        transform.position = Vector3.Lerp (transform.position, targetCamPos, smoothing * Time.deltaTime);
    }
}
var target : Transform;            // The position that that camera will be following.
var smoothing : float = 5f;        // The speed with which the camera will be following.

private var offset : Vector3;                     // The initial offset from the target.

function Start ()
{
    // Calculate the initial offset.
    offset = transform.position - target.position;
}


function FixedUpdate ()
{
    // Create a postion the camera is aiming for based on the offset from the target.
    var targetCamPos : Vector3 = target.position + offset;

    // Smoothly interpolate between the camera's current position and it's target position.
    transform.position = Vector3.Lerp (transform.position, targetCamPos, smoothing * Time.deltaTime);
}

Related tutorials