Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Help with clamping my rts camera controller

Discussion in 'Scripting' started by Deleted User, May 4, 2023.

  1. Deleted User

    Deleted User

    Guest

    I have been having some trouble clamping my cameras y rotation, I tried to clamp both yrotation and also mousey but it do not seem to work any help is welcome!

    WHOLE SCRIPT;
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CameraController : MonoBehaviour
    6. {
    7.     public Transform cameraObject;
    8.  
    9.     public float panSpeed = 10f;
    10.     public float rotationSpeed = 10f;
    11.     public float mouseRotation = 1f;
    12.     public float rotTime = 1f;
    13.     public float zoomSpeed = 1f;
    14.     public float minGroundDistance = 1f;
    15.  
    16.     private Quaternion initialRotation;
    17.     private Quaternion yRotation;
    18.     private Quaternion xRotation;
    19.  
    20.     private void Awake()
    21.     {
    22.         initialRotation = transform.rotation;
    23.         yRotation = Quaternion.identity;
    24.         xRotation = Quaternion.identity;
    25.     }
    26.  
    27.     private void Update()
    28.     {
    29.         Pan();
    30.         Rotate();
    31.         Zoom();
    32.     }
    33.  
    34.     private void Pan()
    35.     {
    36.         if (Input.GetKey(KeyCode.W))
    37.         {
    38.             transform.Translate(Vector3.forward * panSpeed * Time.deltaTime);
    39.         }
    40.  
    41.         if (Input.GetKey(KeyCode.S))
    42.         {
    43.             transform.Translate(Vector3.forward * -panSpeed * Time.deltaTime);
    44.         }
    45.  
    46.         if (Input.GetKey(KeyCode.A))
    47.         {
    48.             transform.Translate(Vector3.right * -panSpeed * Time.deltaTime);
    49.         }
    50.  
    51.         if (Input.GetKey(KeyCode.D))
    52.         {
    53.             transform.Translate(Vector3.right * panSpeed * Time.deltaTime);
    54.         }
    55.     }
    56.  
    57.     //This is the function where all the rotation of the camera is made CLAMP HELP NEED HERE!
    58.     private void Rotate()
    59.     {
    60.         if (Input.GetKey(KeyCode.E))
    61.         {
    62.             yRotation *= Quaternion.Euler(Vector3.up * rotationSpeed * Time.deltaTime);
    63.         }
    64.  
    65.         if (Input.GetKey(KeyCode.Q))
    66.         {
    67.             yRotation *= Quaternion.Euler(Vector3.up * -rotationSpeed * Time.deltaTime);
    68.         }
    69.  
    70.         if (Input.GetMouseButton(1))
    71.         {
    72.             float mouseX = Input.GetAxis("Mouse X") * mouseRotation;
    73.             float mouseY = Input.GetAxis("Mouse Y") * mouseRotation;
    74.  
    75.             yRotation *= Quaternion.Euler(Vector3.up * mouseX);
    76.  
    77.             xRotation *= Quaternion.Euler(Vector3.right * -mouseY);
    78.         }
    79.  
    80.         transform.rotation = initialRotation * yRotation * xRotation;
    81.     }
    82.  
    83.     private void Zoom()
    84.     {
    85.         float zoomAmount = Input.GetAxis("Mouse ScrollWheel") * zoomSpeed;
    86.         Vector3 targetPosition = cameraObject.position + cameraObject.forward * zoomAmount;
    87.         cameraObject.position = Vector3.Lerp(cameraObject.position, targetPosition, Time.deltaTime * zoomSpeed);
    88.     }
    89. }
    ONLY ROTATION METHOD:
    Code (CSharp):
    1.    
    2. private void Rotate()
    3.     {
    4.         if (Input.GetKey(KeyCode.E))
    5.         {
    6.             yRotation *= Quaternion.Euler(Vector3.up * rotationSpeed * Time.deltaTime);
    7.         }
    8.  
    9.         if (Input.GetKey(KeyCode.Q))
    10.         {
    11.             yRotation *= Quaternion.Euler(Vector3.up * -rotationSpeed * Time.deltaTime);
    12.         }
    13.  
    14.         if (Input.GetMouseButton(1))
    15.         {
    16.             float mouseX = Input.GetAxis("Mouse X") * mouseRotation;
    17.             float mouseY = Input.GetAxis("Mouse Y") * mouseRotation;
    18.  
    19.             yRotation *= Quaternion.Euler(Vector3.up * mouseX);
    20.  
    21.             xRotation *= Quaternion.Euler(Vector3.right * -mouseY);
    22.         }
    23.  
    24.         transform.rotation = initialRotation * yRotation * xRotation;
    25.     }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,708
    Camera stuff is pretty tricky... you may wish to consider using Cinemachine from the Unity Package Manager.

    There's even a dedicated forum: https://forum.unity.com/forums/cinemachine.136/

    Otherwise if you insist on rolling your own above, then it is...

    ... Time to start debugging! Here is how you can begin your exciting new debugging adventures:

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

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    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 names of the GameObjects or Components involved?
    - 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.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    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.

    Visit Google for how to see console output from builds. 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: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    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:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
     
  3. Elhimp

    Elhimp

    Joined:
    Jan 6, 2013
    Posts:
    71
    Don't change Quaternion, change floats. And then apply this floats as quaternion.
    Code (CSharp):
    1. float xAngle;
    2. float yAngle;
    3.  
    4. void Rotate(float x, float y) {
    5.     xAngle = Mathf.Clamp(xAngle + x, 30, 90);
    6.     yAngle = Mathf.Clamp(yAngle + y, -90, 90);
    7.     transform.rotation = Quaternion.Euler(xAngle, yAngle, 0);
    8. }
    Keep the numbers you can understand if it ain't hitting performance. Or even when it does, if you aren't getting whats going on under the hood.
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,842
    No don't do that. Work with quaternions, otherwise you'll gimp yourself with rotations forever.

    Use Quaternion.AngleAxis to generate a rotation around the up axis, then just multiply two rotations together. The order of operation matters here, so you'll often multiple the rotation you want to add by your current rotation.

    This is a minimum example of how to rotate something only on the y-axis:
    Code (CSharp):
    1. public class RotateBehaviour : Monobehaviour
    2. {
    3.     public float _rotationSpeed = 10f;
    4.  
    5.     private void Update()
    6.     {
    7.         float value = Input.GetAxis("Horizontal");
    8.         Quaternion rotation = Quaternion.AngleAxis(Vector3.up, _rotationSpeed * value);
    9.         transform.rotation = rotation * transform.rotation;
    10.     }
    11. }
     
  5. tassarho

    tassarho

    Joined:
    Aug 25, 2019
    Posts:
    64
    I struggle for SO long trying to clamp my camera without having the camera to be parented to an other empty gameobject. i finally found a solution that work (code below is how my rts camera work).
    I used Unity.Mathematics.quaternion because for reason beyond my knowledge the speed of rotation is not the same if you use UnityEngine.Quaternion multiplication and Unity.Mathematics.quaternion mul, the Quaternion for some reason, make rotation with a value of 1 much slower forcing me to apply multiply the rotation speed by 10, But both work
    Code (CSharp):
    1.         private Quaternion GetCameraRotation()
    2.         {
    3.             if (mouseEndPosition == mouseStartPosition) return cameraTransform.rotation;
    4.             Quaternion rotation = cameraTransform.rotation;
    5.            
    6.             Vector2 distanceXY = (mouseEndPosition - mouseStartPosition) * RotationSpeed;
    7.            
    8.             rotation = RotateFWorld(rotation ,0f, distanceXY.x * Time.deltaTime,0f);//Rotation Horizontal
    9.             rotation = RotateFSelf(rotation,-distanceXY.y * Time.deltaTime, 0f, 0f);//Rotation Vertical
    10.            
    11.             float clampedXAxis = ClampAngle(rotation.eulerAngles.x, MinClamp, MaxClamp); //Min= -30, Max = 70
    12.             rotation.eulerAngles = new Vector3(clampedXAxis, rotation.eulerAngles.y, 0);
    13.            
    14.             mouseStartPosition = mouseEndPosition;
    15.             return rotation;
    16.            
    17.             float ClampAngle(float lfAngle, float lfMin, float lfMax)
    18.             {
    19.                 lfAngle += lfAngle < -180f ? 360f : 0;
    20.                 lfAngle -= lfAngle > 180f ? 360f : 0;
    21.                 return Mathf.Clamp(lfAngle, lfMin, lfMax);
    22.             }
    23.  
    24.             Quaternion RotateFWorld(in Quaternion rotation, float x, float y, float z)
    25.             {
    26.                 quaternion eulerRot = quaternion.EulerZXY(x, y, z);
    27.                 return mul(eulerRot, rotation);
    28.             }
    29.            
    30.             Quaternion RotateFSelf(in Quaternion localRotation, float x, float y, float z)
    31.             {
    32.                 quaternion eulerRot = quaternion.EulerZXY(x, y, z);
    33.                 return mul(localRotation, eulerRot);
    34.             }
    35.         }