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

[RequireComponent(typeof(RopeSim))]
public class RopeCollider : MonoBehaviour {
    private List<Collider> colliders = new List<Collider>();
    private RopeSim ropesim;
    void Start () {
        ropesim = GetComponent<RopeSim>();
        if ( !ropesim.sane ) {
            return;
        }
        foreach( Collider col in colliders ) {
            Destroy(col);
        }
        colliders.Clear();
        foreach( Transform bone in ropesim.bones ) {
            CapsuleCollider col = bone.gameObject.AddComponent<CapsuleCollider>();
            col.isTrigger = true;
            col.radius = 0.25f;
            colliders.Add(col);
        }
    }

    void Update() {
        if ( colliders.Count != ropesim.bones.Count ) {
            Start();
            return;
        }
        for (int i=1;i<ropesim.bones.Count;i++ ) {
            CapsuleCollider col = ropesim.bones[i-1].gameObject.GetComponent<CapsuleCollider>();
            col.height = Vector3.Distance( ropesim.bones[i-1].position, ropesim.bones[i].position );
            col.center = new Vector3 (0, col.height, 0 );
        }
    }
}
