Horizontal slider and camera

Hello
I have a problem with HorizontalSlider and Camera. I need to move the camera with the
horizontalSlider. (for zoomIn and ZoomOut)

This is my current code:

public class TopPanelMenu : MonoBehaviour {

public GUIStyle myStyle;
public float hSliderValue = 0.0F;

public Rect sliderRect;

void OnGUI()
{

    sliderRect = new Rect(200, 25, 170, 10);
    GUI.BeginGroup(new Rect(10.5f, 10.5f, 700, 200));
    {
        GameObject obj = GameObject.FindGameObjectWithTag("MainCamera");
        Camera cam = obj.GetComponent<Camera>() as Camera;

        GUI.Box(new Rect(0, 0, 550, 100), "Camera", GUI.skin.GetStyle("box"));
         // First button
        if (GUI.Button(new Rect(10, 25, 170, 40), "zoom", GUI.skin.GetStyle("button")))
        {
            
            
        }

        hSliderValue = GUI.HorizontalSlider(sliderRect, hSliderValue, 0.0f, 10.0f);

        cam.transform.Translate(0, 0, hSliderValue);

       
        
        
    }
    GUI.EndGroup();
}

}

With this code, I can move the camera, but when I move it, this does not stop.

appreciate your help

In the cam.transform.Translate(0, 0, hSliderValue);

You should not to use Translate, you should use position.

cam.transform.position = Vector3(0,0,hSliderValue);

but if you want to zoom in and zoom out, I have a good idea to make it good.

change

cam.transform.Translate(0, 0, hSliderValue); 

to

cam.fieldOfView = hSliderValue;

Translate will result in a relative movement. As long as your hSliderValue is not 0.0 it will move. The actual value will just determine how fast it is moving. Since you only accept values between 0 and 10 you can only move “forward”.

I guess you don’t intended an accelerated movement :wink: so translate is not the right function for your problem then.

Vector3 camPosition = cam.transform.position;
camPosition.z = hSliderValue;
cam.transform.position = camPosition;

If your camera should move from it’s start position 0-10 forward you should save the start z value and add it: camPosition.z = hSliderValue + startValue;

If you wanted an accelerated movement it gets a bit tricky. You should define a deadzone around 0 and the slider value should go from -10 to 10. You should also multiply the movement by Time.deltaTime to make the movement framerate-independent.

ohh and btw. this code:

GameObject obj = GameObject.FindGameObjectWithTag("MainCamera");
Camera cam = obj.GetComponent<Camera>() as Camera;

is exactly the same as

Camera cam = Camera.main;

Thank you very much by your help

I understand the Bunny83 idea, I did not think adding the current position in the z axis of the camera.