How would I connect a rigidbody to another rigidbody during play?

For example, let’s say I have a rectangle. During play, I want to be able to click on the end of the rectangle and spawn another rectangle that is attached to it by a joint.

How would I go about doing this?

EDIT: Better way of asking this that’s more specific:

How would I make a script that would let me click on a little bubble on the end of a rectangle that would spawn an identical rectangle, with the two being attached end-to-end by a joint.

1 Answer

1

To spawn an object and attach it on mouse down you could use

void OnMouseDown()
{
    Transform newRectangle = (MonoBehaviour.Instantiate(Resources.Load("Rectangle")) as GameObject).transform;

    //Need code here to move the newRectangle to the right of the first rectangle

    //Get the hinge joint associated with the first rectangle
    HingeJoint joint = rectangle.GetComponent<HingeJoint>();
    joint.connectedBody = newRectangle.rigidbody;
}

For this your rectangle objects would need a HingeJoint (Or whatever joint you want) defined in the prefab. I’d also assume your bubble has a collider and a reference to the rectangle currently attached to it.