Code Help, Clamping Angle

I’ve been working on writing a function to clamp my camera angle and I’m having trouble figuring out how to slow down the movement as it nears the upper and lower bounds. I’ll post the code below and then explain the problem.

    void CameraHeight(float direction)
        direction *= -1; // todo add an inversion control here

        Vector3 upVector = Vector3.up;

        Vector3 referenceRight = Vector3.Cross(Vector3.forward, upVector);

        Vector3 newDirection = Camera.main.transform.position - player.transform.position;

        float currentAngle = Vector3.Angle(newDirection, upVector);

        if(currentAngle > maxCameraAngle) { direction = 0; }
        if(currentAngle < minCameraAngle) { direction = 0; }

        Camera.main.transform.Translate(0f, direction, 0f);

        if (currentAngle > maxCameraAngle)
            direction = cameraBounceBack;
            Camera.main.transform.Translate(0f, direction, 0f);
        if(currentAngle < minCameraAngle)
            direction = -cameraBounceBack;
            Camera.main.transform.Translate(0f, direction, 0f);

The direction argument that’s being passed in is the Mouse Y axis. What happens is if the mouse is moving too fast, the camera will get stuck below or above its limit for a few seconds until it bounces back from those two conditionals at the end. I’m hoping there’s a simple way to do this that I’m just overlooking. Thanks in advance for any insights.

Edit: I managed to figure out a crude way to get the clamping to work. I’ll revisit later when I’m feeling more mathy.

Hi Zafaron,

What you could do to solve this problem is to use a bezier curve to design the behaviour. Here is an example from webdesign. You will probably have to write your own algorithm.

Alternatively, a simple parabola could do the job. Here is an example of what I mean:


The input would be on the x axis, the output on the y axis.

I hope this helps. :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms