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

public class RopeJoint : MonoBehaviour
{
    public Rigidbody rb;
    public Rigidbody connectedBody;
    public float maxDistance;

    private void FixedUpdate()
    {
        if ((transform.position - connectedBody.transform.position).magnitude > maxDistance)
        {
            Vector3 dir = (connectedBody.transform.position - transform.position).normalized;
            float mag = (connectedBody.transform.position - transform.position).magnitude;
            float changeValue = mag - maxDistance;
            if (connectedBody.isKinematic && rb.isKinematic)
            {
                return;
            }
            else if (connectedBody.isKinematic)
            {
                transform.position += changeValue * dir;
            }
            else if (rb.isKinematic)
            {
                connectedBody.transform.position -= changeValue * dir;
            }
            else
            {
                transform.position += changeValue * rb.mass / (rb.mass + connectedBody.mass) * dir;
                connectedBody.transform.position -= changeValue * connectedBody.mass / (rb.mass + connectedBody.mass) * dir;
            }
        }
    }
}
