Obi provides a very versatile component to modify the length of a rope at runtime: ObiRopeCursor. When added to a ObiRope, this component will place a cursor on top of it that allows you to 'add' or 'remove' rope from that point, in either direction. Think of it as a regular cursor in a text-editing app: you can place it anywhere in the text and add/remove characters at its location.
You only need to call its ChangeLength(length) method at runtime. The cursor will automatically take care of adding/removing particles/constraints to/from the rope to obtain the new length.
It only has a couple properties, that control its position along the rope and the direction it should be facing:
This is the normalized position of the cursor. 0 will place it at the start of the rope, 1 will place it at the end. Any value it between will place it in the particle closest to that value.
Boolean value that controls the direction of the cursor. Enabling it will make the cursor point towards the end of the rope. Disabling it will make it point towards the start.
So for instance, if you wanted to add new particles to the rope at the middle of it, and make it grow towards its end (you might have fixed/pinned some particles at the start and want them to stay that way) you'd set the cursor's normalized position to 0.5f and its direction to true.
It is very useful to know the current length of the rope when working with cursors. Use the rope's RestLength property for this. The following code increases or reduces rope length using the W and S keys. You can also control the speed of the change:
using System.Collections; using System.Collections.Generic; using UnityEngine; using Obi; public class RopeLengthController : MonoBehaviour { public float speed = 1; ObiRopeCursor cursor; ObiRope rope; void Start () { cursor = GetComponentInChildren<ObiRopeCursor>(); rope = cursor.GetComponent<ObiRope>(); } void Update () { if (Input.GetKey(KeyCode.W)) cursor.ChangeLength(rope.restLength - speed * Time.deltaTime); if (Input.GetKey(KeyCode.S)) cursor.ChangeLength(rope.restLength + speed * Time.deltaTime); } }