Clamp down! ..but in a good way.

Good morning to the might Unity Hive Mind!
I seek guidance from the Oracle.

I have a script for orbiting around an object using the mouse created by some one far more experienced than I at coding (Thank you!). Works well, but I’d like to clamp the ability to “scroll wheel” zoom out. Right now you can back out all the way to Albuquerque but I need to limit it to like 10 meters. I’m assuming some kind of "Mathf.Clamp deal (like there is on rotation) I’m just not sure where to implement it, or how the syntax would be structured.
If anyone would know it’d be… well, all of you!
Any ideas?

public class AltenateCameraOrbit : MonoBehaviour
{
    public GameObject target;
    public float distance = 10.0f;

    public float xSpeed = 250.0f;
    public float ySpeed = 120.0f;

    public float yMinLimit = -20;
    public float yMaxLimit = 80;

    float x = 0.0f;
    float y = 0.0f;

    void Start()
    {
        var angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;
    }

    float prevDistance;

    void LateUpdate()
    {
        if (distance < 2) distance = 2;
        distance -= Input.GetAxis("Mouse ScrollWheel") * 2;
        if (target && (Input.GetMouseButton(0) || Input.GetMouseButton(1)))
        {
            var pos = Input.mousePosition;
            var dpiScale = 1f;
            if (Screen.dpi < 1) dpiScale = 1;
            if (Screen.dpi < 200) dpiScale = 1;
            else dpiScale = Screen.dpi / 200f;

            if (pos.x < 380 * dpiScale && Screen.height - pos.y < 250 * dpiScale) return;

            // comment out these two lines if you don't want to hide mouse curser or you have a UI button
            //Cursor.visible = false;
            //Cursor.lockState = CursorLockMode.Locked;

            x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
            y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

            y = ClampAngle(y, yMinLimit, yMaxLimit);
            var rotation = Quaternion.Euler(y, x, 0);
            var position = rotation * new Vector3(0.0f, 0.0f, -distance) + target.transform.position;
            transform.rotation = rotation;
            transform.position = position;

        }
        else
        {
            // comment out these two lines if you don't want to hide mouse curser or you have a UI button
            //Cursor.visible = true;
            //Cursor.lockState = CursorLockMode.None;
        }

        if (Mathf.Abs(prevDistance - distance) > 0.001f)
        {
            prevDistance = distance;
            var rot = Quaternion.Euler(y, x, 0);
            var po = rot * new Vector3(0.0f, 0.0f, -distance) + target.transform.position;
            transform.rotation = rot;
            transform.position = po;
        }
    }

    static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360)
            angle += 360;
        if (angle > 360)
            angle -= 360;
        return Mathf.Clamp(angle, min, max);
    }
}

maybe after this line…
“distance -= Input.GetAxis(“Mouse ScrollWheel”) * 2;”
some kind of
“return mathf.Clamp(distance, min, max”?

not sure…

That is a LOT of code for what you describe.

Usually one has an axis of control, a single float number such as “distance from look target.”

You would adjust, clamp and use that axis to compute the regard position.

In any case, camera stuff is pretty tricky… you may wish to consider using Cinemachine from the Unity Package Manager.

If you wish to debug what all is happening above, here is how to proceed:

You must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

Thanks so much for the well thought out response! That’s a whole lot of good intel and ideas!
That said…
I feel kinda like a guy who asked for sandwich, and then you sat down and gave a complete and insightful lecture on the history of French Cuisine. Very complete and nuanced. …but now… I kinda still just want my sandwich…
I’m so far into the project and coming up on delivery, I’d love to just fix this particular code and wrap this up.
So again, thank you so much for this info, but could you guide me to the solution at hand?

Much respect,
Jeff

That was the second part of my post, starting with “If you wish to debug…”

Staring at code is not generally helpful. You have to debug it and find out what it is doing.