在Unity中相机平滑缩放问题

时间:2019-03-18 20:54:52

标签: c# unity3d camera zoom

我试图让我的相机在每次使用鼠标滚轮时都能平滑地放大和缩小,但是由于某种原因,它会立即放大而不平滑。

这就是我更新缩放的方式:

[SerializeField, Range(10, 100)] float scrollSpeed = 10f;
[SerializeField] Vector2 zoomAmount = Vector2.zero;

private float ScrollWheel
{
    get { return Input.GetAxis("Mouse ScrollWheel"); }
}

private new Camera camera = null;

void Update()
{
    if (camera == null) return;

    UpdateZoom();
}

void UpdateZoom()
{
    pos = camera.transform.position;

    pos = Vector3.Lerp(pos, new Vector3(pos.x, pos.y - scrollSpeed * 10 * ScrollWheel, pos.z), Time.deltaTime * 2);
    pos.y = Mathf.Clamp(pos.y, zoomAmount.x, zoomAmount.y);

    camera.transform.position = pos;
}

1 个答案:

答案 0 :(得分:2)

我认为您对Lerp感到有些困惑(当我开始使用它时,我也以相同的方式感到困惑)。当您为时间参数(第三个参数)传递0时,它将返回您的“起始”向量。当您为time参数传递一个等于或大于1的值时,它将返回您的“结束”向量。 但是,如果要传递Time.deltaTime * 2,则每帧将返回近似相同的插值矢量。 Lerp不会“跟踪”已经插值的距离,因此,每帧传递相同的时间值,Lerp永远不会真正返回您的结束向量。因此,除了传递Time.deltaTime * 2之外,您需要执行类似的操作

float interpolatedTime = 0;
void Update()
{
   var myVector = Vector3.Lerp(vector1, vector2, this.interpolatedTime);
   this.interpolatedTime += Time.deltaTime; 
}

您的相机怎么样?

float zoomTime;
float zoomTarget;
float lastScrollWheelDirection;

void Update()
{
    // If this camera is currently zooming in and the player started zooming
    // out (or vice versa), reset the amount that is remaining to be zoomed
    if ((this.lastScrollWheelDirection > 0 && this.ScrollWheel < 0) ||
        (this.lastScrollWheelDirection < 0 && this.ScrollWheel > 0))
    {
        this.zoomTarget = 0;
    }
    if (this.ScrollWheel != 0)
    {
        this.lastScrollWheelDirection = this.ScrollWheel;
    }

    // zoomTarget is the total distance that is remaining to be zoomed.
    // Each frame that the scroll wheel is moved, we'll add a little more
    // to the distance that we want to zoom
    zoomTarget += this.ScrollWheel * this.scrollSpeed;

    // zoomTime is used to do linear interpolation to create a smooth zoom.
    // Each time the player moves the mouse wheel, we reset zoomTime so that 
    // we restart our linear interpolation
    if (this.ScrollWheel != 0)
    {
        this.zoomTime = 0;
    }

    if (this.zoomTarget != 0)
    {
        this.zoomTime += Time.deltaTime;

        // Calculate how much our camera will be moved this frame using linear
        // interpolation.  You can adjust how fast the camera zooms by
        // changing the divisor for zoomTime
        var translation = Vector3.Lerp(
            new Vector3(0, 0, 0),
            new Vector3(0, this.zoomTarget, 0),
            zoomTime / 4f);   // see comment above

        // Zoom the camera by the amount that we calculated for this frame
        this.transform.position -= translation;

        // Decrease the amount that's remaining to be zoomed by the amount 
        // that we zoomed this frame
        this.zoomTarget -= translation.y;
    }
}
相关问题