Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help  Spawning a rope along a line the player draws
#3
Wrote a sample script for you. I'm using the solver's OnSubstep callback instead of LateUpdate, because I'm setting the first two particle positions every simulation step in order for the rope to roughly follow the direction of the cursor instead of increasing its length in whatever the current direction of the tip is.

Also I'm raycasting against the XZ plane which might not be how your interaction system works, but the important parts should be easy to port to your system:

Code:
using UnityEngine;
using Obi;

[RequireComponent(typeof(ObiRope))]
public class DrawRope : MonoBehaviour
{
    public float directionSmoothing = 0.9f;

    public ObiRopeCursor cursor;
    ObiRope rope;
    Vector3 lastPoint;
    Vector3 avgDir;

    private void Start()
    {
        rope = GetComponent<ObiRope>();
        rope.solver.OnSubstep += Solver_OnBeginStep;
    }
    private void OnDestroy()
    {
        rope.solver.OnSubstep -= Solver_OnBeginStep;
    }

    private void Solver_OnBeginStep(ObiSolver solver, float stepTime)
    {
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Plane p = new Plane(Vector3.up, 0);

        if (p.Raycast(ray, out float enter))
        {
            var point = ray.GetPoint(enter);

            if (Input.GetMouseButtonDown(0))
            {
                lastPoint = point;
            }
            if (Input.GetMouseButton(0))
            {
                float distance = Vector3.Distance(lastPoint, point);
                cursor.ChangeLength(rope.restLength + distance);

// Average cursor movement direction:
                if (distance > 0.0001f)
                    avgDir = Vector3.Lerp(Vector3.Normalize(lastPoint - point), avgDir, directionSmoothing);

// Update the first two particles so that they lie in the direction drawn by the cursor:
                var part1 = rope.elements[0].particle1;
                var part2 = rope.elements[0].particle2;

                rope.solver.positions[part1] = rope.solver.transform.InverseTransformPoint(point);
                rope.solver.velocities[part1] = Vector3.zero;
               
                rope.solver.positions[part2] = rope.solver.transform.InverseTransformPoint(point + avgDir * rope.elements[0].restLength);
                rope.solver.velocities[part2] = Vector3.zero;

                lastPoint = point;
            }
        }
    }
}

Video of results:
Reply


Messages In This Thread
RE: Spawning a rope along a line the player draws - by josemendez - 20-03-2024, 08:10 AM