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

[RequireComponent(typeof(Rigidbody))]
public class GravityController : MonoBehaviour
{
    public GameObject GravityObject;
    private Rigidbody _rigidBody;
    public Vector3 InitialForce = Vector3.zero;
    public float DistanceTolerance = 0.01f;
    public bool LinkUp = true;
    public bool FixedDistance = true;

    // Start is called before the first frame update
    void Start()
    {
        if (GravityObject == null)
        {
            GravityObject = GameObject.FindWithTag("GravitySource");
        }
        _rigidBody = GetComponent<Rigidbody>();
        _rigidBody.AddForce(InitialForce, ForceMode.VelocityChange);
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void FixedUpdate()
    {
        ApplyGravity(GravityObject);
        Debug.DrawLine(_rigidBody.transform.position, _rigidBody.transform.position + _rigidBody.velocity, Color.black);
    }

    private void ApplyGravity(GameObject gravityObject)
    {
        float distanceToMassCenter = Vector3.Distance(_rigidBody.transform.position, gravityObject.transform.position);
        Vector3 normalToMassCenter = Vector3.Normalize(_rigidBody.transform.position - gravityObject.transform.position);
        Vector3 gravity = -1.0f * normalToMassCenter * (1.0f / distanceToMassCenter) * _rigidBody.mass;
        _rigidBody.AddForce(gravity, ForceMode.Acceleration);
              
    }

    void OnCollisionEnter(Collision collision)
    {
        foreach (ContactPoint contact in collision.contacts)
        {
            Debug.DrawRay(contact.point, contact.normal, Color.white);
        }
        
    }

}
