The Wolf
The Wolf

Reputation: 55

how to limit and clamp distance between two points in a Line renderer unity2d

I am making a game which let you click on a ball and drag to draw a line renderer with two points and point it to a specific direction and when release I add force to the ball, for now, I just want to know how can I limit the distance between those two points like give it a radius.

You can take a look at here.

Upvotes: 0

Views: 3680

Answers (2)

derHugo
derHugo

Reputation: 90610

You can simply clamp it using a Mathf.Min.

Since you didn't provide any example code unfortunately here is some example code I made up with a simple plane with a MeshCollider, a child object with the LineRenderer and a camera set to Orthographic. You probably would have to adopt it somehow.

public class Example : MonoBehaviour
{
    // adjust in the inspector
    public float maxRadius = 2;

    private Vector3 startPosition;

    [SerializeField] private LineRenderer line;
    [SerializeField] private Collider collider;
    [SerializeField] private Camera camera;

    private void Awake()
    {
        line.positionCount = 0;

        line = GetComponentInChildren<LineRenderer>();
        collider = GetComponent<Collider>();
        camera = Camera.main;
    }

    // wherever you dragging starts
    private void OnMouseDown()
    {
        line.positionCount = 2;

        startPosition = collider.ClosestPoint(camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z)));

        var positions = new[] { startPosition, startPosition };

        line.SetPositions(positions);
    }

    // while dragging
    private void OnMouseDrag()
    {
        var currentPosition = GetComponent<Collider>().ClosestPoint(camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z)));

        // get vector between positions
        var difference = currentPosition - startPosition;

        // normalize to only get a direction with magnitude = 1
        var direction = difference.normalized;

        // here you "clamp" use the smaller of either
        // the max radius or the magnitude of the difference vector
        var distance = Mathf.Min(maxRadius, difference.magnitude);


        // and finally apply the end position
        var endPosition = startPosition + direction * distance;

        line.SetPosition(1, endPosition);
    }
}

This is how it could look like

enter image description here

Upvotes: 4

Jamal Alkelani
Jamal Alkelani

Reputation: 618

I've written the following pseudo code, which may help you

float rang ;

Bool drag=true; 
GameObject ball;

OnMouseDrag () { 
if(drag) { 
//Put your dragging code here

}

if (ball.transform.position>range)
     Drag=false;
else Drage=true;

}

Upvotes: 0

Related Questions