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

public class Attractor : MonoBehaviour
{
    // our gravity constant (the real one is much smaller)
    const float G = 6.67f;
    // this rigid body
    public Rigidbody rb;

    // List of all attractors to keep things fast
    public static List<Attractor> Attractors;

    // when this object is enabled or disabled, add/remove from the attractor list
    void OnEnable () {
        if(Attractors == null)
            Attractors = new List<Attractor>();

        Attractors.Add(this);
    }
    void OnDisable() {
        Attractors.Remove(this);
    }

    void FixedUpdate() { 
        // cycle through all objects with attractors
        foreach (Attractor attractor in Attractors) {
            if(attractor != this)
                Attract(attractor);
        }
    }

    void Attract(Attractor objToAttract) {
        // Gravitational attraction!
        // F = G * (m1 * m2)/ d^2

        // grab the other rigid body
        Rigidbody rbToAttract = objToAttract.rb;

        // calculate the direction of the attractor
        Vector3 direction = rb.position - rbToAttract.position;
        // get the distance between the two
        float distance = direction.magnitude;

        if(distance == 0f) return; // prevent division by zero errors

        // calculate the amount of force based on the equation at the top
        float forceMagnitude = G * (rb.mass * rbToAttract.mass) / Mathf.Pow(distance, 2);
        // create the final force vector (direction and magnitude)
        Vector3 force = direction.normalized * forceMagnitude;

        // add the force to the object
        rbToAttract.AddForce(force);
    }
}
