放大一定距离

时间:2019-09-15 15:03:57

标签: c# unity3d math

我有以下Unity脚本

void Update()
{
    Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit = new RaycastHit();

    if(Physics.Raycast(mouseRay, out hit))
    {
        if (Input.GetMouseButtonDown(0))
        {
            Camera.main.GetComponent<CameraController>().ZoomIn(hit.transform.position);
        }
    }
}

然后在我拥有的相机中

public void ZoomIn(Vector3 target)
{
    zoomSavePosition = camera.transform.position;
    StartCoroutine(Zoom(zoomSavePosition, target, zoomDuration));
}


// ZoomRoutine
IEnumerator Zoom(Vector3 from, Vector3 to, float duration)
{
    float time = 0;
    Quaternion rotation = camera.transform.rotation;
    Quaternion targetRotation = Quaternion.LookRotation(to - camera.transform.position);
    while (time < zoomDuration)
    {
        camera.transform.position = Vector3.Lerp(from, to, time / zoomDuration);
        camera.transform.rotation = Quaternion.Slerp(rotation, targetRotation, time / zoomDuration);

        time += TimeManager.instance.deltaTime;
        yield return null;
    }

    camera.transform.position = to;
    camera.transform.rotation = targetRotation;
}

这很好用,但是可以在对象内部放大。无论从何处到什么,我都希望始终缩放并以与目标相同的距离结束。

我本来打算使用MoveTowards,但是在协程内部这将使运动停止,但是旋转将继续进行(这是一个很丑陋的问题)

因此,给一个点A和一个点B,我如何计算中间的距离,该距离设置为与B总是相同?

1 个答案:

答案 0 :(得分:1)

要缩放到与目标对象的特定距离,您需要计算相机方向上与目标对象的距离,然后将其减去到目标位置。

var heading = to - from;
var dist = heading.magnitude;
var direction = heading / dist;

Vector3 newTargetPosition = to - (direction * distance);

参考:https://docs.unity3d.com/Manual/DirectionDistanceFromOneObjectToAnother.html

通过此调整,您可以停止缩放到任何提供的距离。 调整后的代码如下所示:

public void ZoomIn(Vector3 target)
{
    float targetDistance = 2f;
    zoomSavePosition = camera.transform.position;
    StartCoroutine(Zoom(zoomSavePosition, target, zoomDuration, targetDistance));
}


// ZoomRoutine
IEnumerator Zoom(Vector3 from, Vector3 to, float duration, float distance)
{
    float time = 0;
    Quaternion rotation = camera.transform.rotation;
    Quaternion targetRotation = Quaternion.LookRotation(to - camera.transform.position);

    var heading = to - from;
    var dist = heading.magnitude;
    var direction = heading / dist;

    Vector3 newTargetPosition = to - (direction * distance);

    while (time < zoomDuration)
    {
        camera.transform.position = Vector3.Lerp(from, newTargetPosition, time / zoomDuration);
        camera.transform.rotation = Quaternion.Slerp(rotation, targetRotation, time / zoomDuration);

        time += Time.deltaTime;
        yield return null;
    }

    camera.transform.position = newTargetPosition;
    camera.transform.rotation = targetRotation;
}

您可以在要停止缩放的位置设置targetDistance的值。