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

public class ShadowCaster : MonoBehaviour
{
    public float maxDist = 2;
    public float minDist = 0;
    public float maxAlpha = 0.3f;

    SpriteRenderer sr;
    Vector3 startScale;
    float z;

    private void Awake() {
        sr = GetComponent<SpriteRenderer>();
        startScale = transform.localScale;
        z = transform.position.z;
    }

    // Update is called once per frame
    void Update() {
        int mask = LayerMask.GetMask("Environment");
        var hit = Physics2D.Raycast(transform.parent.position, Vector2.down, 5f, mask);
        if (hit.collider != null) {
            Vector3 pos = hit.point;
            pos.z = z;
            transform.position = pos;
            transform.localScale = startScale * hit.distance.Map(minDist, maxDist, 1, 0);
            Color c = sr.color;
            c.a = hit.distance.Map(minDist, maxDist, maxAlpha, 0f);
            sr.color = c;
        }
    }

    private void LateUpdate() {
        transform.rotation = Quaternion.identity;
    }
}
