简体   繁体   中英

Clamping my camera to a min and max value

I tried many approaches, watched tutorials but can't wrap my head around to make the clamp work with my code that I have right now.

So I can zoom in and out but infinitely, how to clamp the camera to max value -5 which is slightly above my player, and min value around -15 which is far above my player.

// Control the distance between the object && camera
    private void ZoomIntoObject(float maxZoom, float minZoom)
    {     
        float scrollInput = Input.GetAxis("Mouse ScrollWheel");
        //zPos = scrollInput;
        // zPos = Mathf.Clamp(zPos, minZoom, maxZoom);

        // While scrollwheel
        if (scrollInput > 0.0f)
        {
            // Move forward on the z-as && Clamp maxZoom
            transform.position += transform.forward;
        } else if (scrollInput < 0.0) {
            // Move forward on the z-as && Clamp maxZoom
            transform.position -= transform.forward;
        }

        Debug.Log(zPos);
    }

Calculate your new position, clamp its z component, then assign to position.

private void ZoomIntoObject(float maxZoom, float minZoom)
{     
    float scrollInput = Input.GetAxis("Mouse ScrollWheel");

    Vector3 newPos = transform.position;
    if (scrollInput > 0.0f)
    {
        newPos  += transform.forward;
    } else if (scrollInput < 0.0) {
        newPos  -= transform.forward;
    }
    
    newPos.z = Mathf.Clamp(newPos.z, minZoom, maxZoom);
    transform.position = newPos;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM