jozza710
jozza710

Reputation: 95

Clamp Diagonal Movement / Clamp Camera Zoom

I am trying to make my camera zoom in and out but I want to lock the amount in which it can zoom. I have tried a few things although they haven't achieved the outcome I was hoping for. My camera is sitting at a rotation of 65 degrees on the X axis and I want to move it along that diagonal axis. Thanks in advance!

Camera.main.transform.Translate(0,0, Input.mouseScrollDelta.y * zoomSpeed * Time.deltaTime);

The code above zooms the camera in the way that I want although I am unsure how to clamp the values.

    cameraDistance += Input.mouseScrollDelta.y * zoomSpeed * Time.deltaTime;
    cameraDistance = Mathf.Clamp(cameraDistance, minCameraDistance, maxCameraDistance);
    Camera.main.transform.localPosition = (new Vector3(0, -cameraDistance, 0));

The code above clamps the value but only moves in an upwards direction

    cameraDistance += Input.mouseScrollDelta.y * zoomSpeed * Time.deltaTime;
    cameraDistance = Mathf.Clamp(cameraDistance, minCameraDistance, maxCameraDistance);
    Camera.main.fieldOfView = -cameraDistance;

The code above clamps the value and keeps my rotation focused on the player although it distorts the view to much.

NOTE! I definitely don't want change my cameras field of view!

Upvotes: 1

Views: 435

Answers (1)

josehzz
josehzz

Reputation: 393

You can still use the first line of code that works, just add some more logic.

//Checks if camera is inside of bounds
if(Vector3.Distance(Camera.main.transform.position, targetObject.position) >= minCameraDistance &&
   Vector3.Distance(Camera.main.transform.position, targetObject.position) <= maxCameraDistance) {
    //Do Translation
    Camera.main.transform.Translate(0, 0, Input.mouseScrollDelta.y * zoomSpeed * Time.deltaTime);
}
else if (Vector3.Distance(Camera.main.transform.position, targetObject.position) < minCameraDistance) { //Checks if camera is too close to the target
    Camera.main.transform.Translate(0, 0, Vector3.Distance(Camera.main.transform.position, targetObject.position) - minCameraDistance + Mathf.Epsilon);
}
else if (Vector3.Distance(Camera.main.transform.position, targetObject.position) > maxCameraDistance) { //Check if the camera is too far from the target
    Camera.main.transform.Translate(0, 0, Vector3.Distance(Camera.main.transform.position, targetObject.position) - maxCameraDistance + Mathf.Epsilon);
}

I added a targetObject(Transform variable) that represents the object from where the distance is calculated.

Change that to any object or Vector3 to pivot the camera. Ex: if it is the origin put Vector3.zero instead of targetObject.position

The two else if statements clamps the values so camera doesn't go too close or too far away from the minCameraDistance and maxCameraDistance values.

Upvotes: 1

Related Questions