- Home /
Help needed on getting distance value of chain of links after instantiation
using UnityEngine;
public class Rope : MonoBehaviour
{
public GameObject hook;
public GameObject linkEnd;
public GameObject linkPrefab;
public int links;
public float range;
public float maxRange;
void Start ()
{
GenerateRope();
}
private void Update()
{
GetRange();
}
private void GenerateRope()
{
Rigidbody2D previousRB = hook.GetComponent<Rigidbody2D>();
for (int i = 0; i < links; i++)
{
GameObject link = Instantiate(linkPrefab, transform);
HingeJoint2D Hinge = link.GetComponent<HingeJoint2D>();
DistanceJoint2D Distance = link.GetComponent<DistanceJoint2D>();
Hinge.connectedBody = previousRB;
Distance.connectedBody = previousRB;
Hinge.autoConfigureConnectedAnchor = false;
Hinge.connectedAnchor = new Vector2(0f, -0.145f);
if (i < links -1)
{
previousRB = link.GetComponent<Rigidbody2D>();
}
else
{
linkEnd.GetComponent<LinkEnd>().ConnectLinkEnd(link.GetComponent<Rigidbody2D>());
}
CalculateLength(links);
}
}
private float GetRange()
{
return range = Vector2.Distance(hook.transform.position, linkEnd.transform.position);
}
private void CalculateLength(int links)
{
DistanceJoint2D distance = linkPrefab.GetComponent<DistanceJoint2D>();
HingeJoint2D anchors = linkPrefab.GetComponent<HingeJoint2D>();
maxRange += distance.distance;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.blue;
Gizmos.DrawLine(hook.transform.position, linkEnd.transform.position);
}
}
Here I have a gameObject that instantiates multiple 'links' (int links) at Start() as children. These chains form a rope and at the end of it, there is a weight connected (GameObject linkEnd). I need two float values in order to make this work with other mechanics; max distance (radius from center to linkEnd's position), and current distance of the same which is tracked real-time. I've managed to get the current distance since it's so simple with VectorX.Distance as shown. However, getting the max distance wasn't. Straight forward max distance of this objects when having 10 and 20 links each gave me number of...
Where x = number of links y = the size / height of each link object and z being the max distance returned by GetRange()
x * y = z
20 * y = 87.39162
y = 4.369581
10 * y = 46.65462
y = 4.665462
it just gets me really confused. Even though this difference of y was occurred by the weight of linkEnd (either are identical) it still doesn't give me an answer.
I've tried to get maxRange via adding up the distance of DistanceJoint attached to each links(since I couldn't use HingeJoint to get the right value either), but no lunk. The returned value was also incorrect.
So, simply put: I need maxRange to be calculated at initiation of this script. Can someone give me some good tips please?
Your answer
![](https://koobas.hobune.stream/wayback/20220612124954im_/https://answers.unity.com/themes/thub/images/avi.jpg)