﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraBackground : MonoBehaviour {
    public Material mat;

    private GameObject bgPlane;
    public Camera cam;
    private MeshRenderer mr;

    // Use this for initialization
    void Start () {
        if (!enabled) return;
        //cam = Camera.main;
        if (!cam)
        {
            Debug.LogError("Attach CameraBackground script to a camera");
            return;
        }
        Mesh mesh = new Mesh();
        Vector3[] verts = new Vector3[4];
        Vector2[] uvs = new Vector2[4];

        float width = cam.pixelWidth; 
        float height = cam.pixelHeight; 
        verts[0] = cam.ScreenToWorldPoint(new Vector3(-width / 2, height, cam.farClipPlane - 0.01f));
        verts[1] = cam.ScreenToWorldPoint(new Vector3(width * 1.5f, height, cam.farClipPlane - 0.01f));
        verts[2] = cam.ScreenToWorldPoint(new Vector3(-width / 2, 0, cam.farClipPlane - 0.01f));
        verts[3] = cam.ScreenToWorldPoint(new Vector3(width * 1.5f, 0, cam.farClipPlane - 0.01f));

        float u = 1f;
        uvs[0] = new Vector2(0, u);
        uvs[1] = new Vector2(u, u);
        uvs[2] = new Vector2(0, 0);
        uvs[3] = new Vector2(u, 0);

        mesh.vertices = verts;
        mesh.uv = uvs;
        mesh.triangles = new int[] { 0, 1, 2, 1, 3, 2 };

        bgPlane = new GameObject("Background Plane", typeof(MeshFilter), typeof(MeshRenderer));
        bgPlane.transform.parent = transform;
        bgPlane.transform.localPosition = Vector3.zero;
        (bgPlane.GetComponent<MeshFilter>() as MeshFilter).mesh = mesh;
        bgPlane.layer = 8;
        mr = bgPlane.GetComponent<MeshRenderer>();
        mr.material = mat;
    }
}
