如何限制和限制线渲染器unity2d中两点之间的距离

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

我正在制作一款游戏,您可以点击球并拖动以绘制带有两个点的线渲染器并将其指向特定方向,松开时我会向球施加力, 现在,我只想知道如何限制这两点之间的距离,比如给它一个半径。

我写了下面的伪代码,可能对你有帮助

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;

}

您可以使用 Mathf.Min 简单地夹住它。

由于您没有提供任何示例代码,很遗憾,这里是一些示例代码,我用一个带有 MeshCollider 的简单平面、一个带有 LineRenderer 的子对象和一个设置为Orthographic。您可能不得不以某种方式采用它。

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);
    }
}

这就是它的样子