Help with camera zoom?

Can anyone tell me what I’m doing wrong, or point me in the right direction? I wrote a script to control my camera. So far I have WASD, mouse wheel zoom, and WASD movement limits working. I’d like to have zoom limits, so the user can’t zoom the camera in too far, or too far out. I tried using mathf.clamp to limit movement in the y direction, which is vertical for me, but it just makes the camera jump continually between the two limits I’ve set. This is my script:

using UnityEngine;
using System.Collections;

public class CamControl : MonoBehaviour {

    public float speed =1;

    // Use this for initialization
    void Start () {
        Cursor.visible = false;
    }
   
    // Update is called once per frame

    void Update () {
        float horz = Input.GetAxis ("Horizontal");
        float vert = Input.GetAxis ("Vertical");
        transform.position += (Vector3.forward * vert + Vector3.right * horz) * speed * Time.deltaTime;
       
        float mousewheel = Input.GetAxis ("Mouse ScrollWheel");
        if (mousewheel != 0)
            transform.position -= Vector3.up * mousewheel * speed * Time.deltaTime *20;
           

        transform.position = new Vector3(Mathf.Clamp(transform.position.x, -40, 40), transform.position.y, Mathf.Clamp(transform.position.z, -60, 40));


    }

Can anyone help?

I see clamps on everything except the Y?

Right, I addressed that in my OP. If I add clamps to the y axis, the camera jumps between each value, several times a second.

Here’s a video showing whats happening: https://vid.me/YYdi

Its actually a lot worse than it looks in the video. I used W10’s game capture utility, and I don’t think it actually can grab each frame.

Well what clamp values did you use?

40 and 35. My camera is set to a Y value of 40 when the scene starts.

Nothing’s jumping out at me for why that wouldn’t work – you put it as 35,40 in the clamp statement, not 40,35 right? The smaller number has to go first.

If that’s not it - try a bigger range, just for debugging, like 20 and 80 and see what happens.

1 Like

That did the trick. I must have been reversing the order, though I didn’t think I was. Thanks for the help. You’ve saved me lots of frustration.

No problem mate - that’s what we’re here for. Glad you got it sorted.