24-05-2023, 11:59 PM
(This post was last modified: 25-05-2023, 12:00 AM by Balin.
Edit Reason: fix code
)
Thanks for the reply.
Instead of increasing strain in the rope by shrinking it, I've instead done what you suggested by setting the rope's velocity after tearing it. As it turns out, this suited my needs much better, and is also much easier to control.
Here's my new code in case anyone's interested:
I managed to fix the rope shrinking problem by setting the Stretching Scale to 1 on the distance constraint, as I had previously misunderstood what this value is used for. Also, after increasing the number of solver iterations for the distance constraint, the rope is much more responsive than it was.
Thanks again.
Instead of increasing strain in the rope by shrinking it, I've instead done what you suggested by setting the rope's velocity after tearing it. As it turns out, this suited my needs much better, and is also much easier to control.
Here's my new code in case anyone's interested:
Code:
using Obi;
using UnityEngine;
public class RopeSnapback : MonoBehaviour
{
public Transform targetA;
public Transform targetB;
public float timeScale;
public float distanceMultiplier;
public float snapPoint; // as a fraction of the rope's length
private ObiRope rope;
void Start()
{
Time.timeScale = timeScale;
rope = GetComponent<ObiRope>();
}
[ContextMenu("Tear")]
public void TearRope()
{
int snapIndex = Mathf.Clamp(Mathf.RoundToInt(rope.elements.Count * snapPoint), 1, rope.elements.Count - 1); // get element from fraction
rope.Tear(rope.elements[snapIndex]);
SetVelocities();
rope.RebuildConstraintsFromElements();
}
private void SetVelocities()
{
Vector4 localTargetA = rope.solver.transform.InverseTransformPoint(targetA.position);
Vector4 localTargetB = rope.solver.transform.InverseTransformPoint(targetB.position);
int elementSnapIndex = Mathf.Clamp(Mathf.RoundToInt(rope.elements.Count * snapPoint), 1, rope.elements.Count - 1);
int solverSnapIndex = rope.elements[elementSnapIndex].particle2;
for (int i = 0; i < rope.solverIndices.Length; i++)
{
int solverIndex = rope.solverIndices[i];
Vector4 target;
// figure out which side of the snap point the current particle is on
if(solverIndex < solverSnapIndex)
{
target = localTargetA;
}
else
{
target = localTargetB;
}
rope.solver.velocities[solverIndex] = (target - rope.solver.positions[solverIndex]) * distanceMultiplier;
}
}
}
I managed to fix the rope shrinking problem by setting the Stretching Scale to 1 on the distance constraint, as I had previously misunderstood what this value is used for. Also, after increasing the number of solver iterations for the distance constraint, the rope is much more responsive than it was.
Thanks again.