Unity 2D games Scripts Game Development

Camerascripts

A few example to inspire you to write the perfect camera script This scripts simply follows the player - reading the player's position and adjusting the camera

public class CameraFollowPlayer : MonoBehaviour
{

    private GameObject _player;

    // Use this for initialization
    void Start () {
        _player = GameObject.FindGameObjectWithTag("Player");

    }

    // Update is called once per frame
    void Update ()
    {
        transform.position = new Vector3(
            _player.transform.position.x,
            _player.transform.position.y,
            transform.position.z);

    }
}

The next script follows the player but you can adjsut the speed so you get a feeling of speed when you move the player

I'm using the Vector3.Lerp() method to create a animation towards the player

using UnityEngine;

public class CameraLerp : MonoBehaviour
{
    private GameObject _player;

    public float Speed;

    // Use this for initialization
    private void Start()
    {
        _player = GameObject.FindGameObjectWithTag("Player");
    }

    // Update is called once per frame
    private void FixedUpdate()
    {
        //Vector3.lerp http://docs.unity3d.com/ScriptReference/Vector3.Lerp.html
        var playerposition = new Vector3(
            _player.transform.position.x,
            _player.transform.position.y,
            transform.position.z);
        transform.position = Vector3.Lerp(transform.position, playerposition, Speed);
    }
}

This variation is using the Vector3.SmoothDamp() method instead of Lerp()

public class CameraDamp : MonoBehaviour
{
    private GameObject _player;
    private Vector3 velocity = Vector3.zero;
    public float SmoothTime;

    void Start () {
        _player = GameObject.FindGameObjectWithTag("Player");
    }

    // Update is called once per frame
    private void Update()
    {
        // vector3.SmoothDamp http://docs.unity3d.com/ScriptReference/Vector3.SmoothDamp.html
        Vector3 targetPosition = new Vector3(
            _player.transform.position.x,
            _player.transform.position.y,
            transform.position.z);

        transform.position = Vector3.SmoothDamp(
            this.transform.position,
            targetPosition,
            ref velocity,
            SmoothTime);
    }
}

In the last example I implement a limitation to the camera so that it does not go out of bounds but stays in the level by adding a minimum and a maximum on the X and Y-axis. Mathf.Clamp() help to easily fix this