首页 > 解决方案 > Unity 中平滑相机缩放的问题

问题描述

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

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

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

标签: c#unity3dcamerazooming

解决方案


我认为您对此有些困惑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;
    }
}

推荐阅读