Implement a limit in Camera Movement

Hello everyone,

I need help with a camera script I’m currently working with.

Here is the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SecurityCameraControl : MonoBehaviour
{
    //public float speedH = 20.0f;            Script for a First Person Camera

    public float rightSpeed = 20.0f;
    public float leftSpeed = -20.0f;

    //public float rotationY = 0.0f;        Script for a First Person Camera

    void Update()
    {
        //rotationY += speedH * Input.GetAxis("Mouse X");            Script for a First Person Camera

        //transform.eulerAngles = new Vector3(0, rotationY, 0);        Script for a First Person Camera

        //rotationY = Mathf.Clamp(rotationY, 50f, 130f);            Script for a First Person Camera

        //EdgeScrolling
        float edgeSize = 40f;
        if (Input.mousePosition.x > Screen.width - edgeSize)
        {
            //EdgeRight
            transform.RotateAround(this.transform.position, Vector3.up, rightSpeed * Time.deltaTime);
        }

        if (Input.mousePosition.x < edgeSize)
        {
            //EdgeRight
            transform.RotateAround(this.transform.position, Vector3.up, leftSpeed * Time.deltaTime);
        }
    }
}

This is the script and I want to implement a limit to the camera so that I can’t rotate 360°.
I already tried to do this in line 20 and it worked, but now I want to transfer that into my real script.

If you need more information please ask me.

Thanks in advance,
Max

Generally never read / write to / from eulerAngles.

The reason is gimbal lock.

Instead track your own float variable that is the heading, adjust and clamp that variable, then “drive” the camera’s rotation each frame.

1 Like

First thanks for your fast answer, but I don’t really understood everythings you said in your answer.

I know what “clamp” means, but how can I track my own float variable, adjust and “drive” that?

  1. declare a variable float heading;

  2. adjust it when conditions warrant:

if (conditionToTurn)
{
   heading += AdjustmentWhateverYouWant;
}
  1. clamp it
heading = Mathf.Clamp( heading, minimum, maximum);
  1. drive the rotation to the camera transform:
cameraTransform.localRotation = Quaterion.Euler( 0, heading, 0);
1 Like

Thank you for your reply.

I tested this out, but I still don’t know how I can apply this into my edgescrolling script. (line 22-34)

It says that I can’t apply that when I try it.

To be clear I already have a thing that defines the heading (line 12 and 20) and in now want to apply this.

Thank you for trying to help me.