0

我正在制作一个游戏,让您单击一个球并拖动以绘制具有两个点的线渲染器并将其指向特定方向,当释放时我向球施加力,现在,我只想知道我该怎么做限制这两点之间的距离,比如给它一个半径。

你可以看看这里。

4

2 回答 2

3

您可以简单地使用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);
    }
}

这就是它的样子

在此处输入图像描述

于 2019-05-27T16:54:41.847 回答
0

我已经编写了以下伪代码,这可能会对您有所帮助

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;

}
于 2019-05-27T01:12:43.970 回答