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

public class TM_Particle_GravityToPoint : MonoBehaviour
{
    public Vector2 GravityPointOffset;
    public ParticleSystem AttachedEmitter;
    public Vector2 GravityTimeMinMax;

    ParticleSystem.Particle[] particles;
    public float GravityRangeInUnits;
    float sqrDist;
    Transform thisTransform;


    void Start()
    {
        thisTransform = transform;
        particles = new ParticleSystem.Particle[ AttachedEmitter.main.maxParticles];
        sqrDist = GravityRangeInUnits * GravityRangeInUnits;
    }


    void LateUpdate()
    {
        float dist;
        int iCount = AttachedEmitter.GetParticles(particles);
        if (iCount > 0)
        {
            for (int i = 0; i < iCount; i++)
            {
                ParticleSystem.Particle p = particles[i];
                dist = Vector3.SqrMagnitude(thisTransform.position - p.position);
                float fLife = p.remainingLifetime / p.startLifetime;

                if (dist < sqrDist)
                {
                    //the particles should slow as they age.
                    particles[i].position = Vector3.Lerp(particles[i].position, Vector3.zero, Time.deltaTime * 2.0f * fLife );
                }
            }
            AttachedEmitter.SetParticles(particles, iCount);
        }
    }

}
