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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Question Problem with RTS style camera. It moves alone. Why?

Discussion in 'Scripting' started by 3dartmike, Oct 7, 2022.

  1. 3dartmike

    3dartmike

    Joined:
    Apr 1, 2020
    Posts:
    13
    Hi, I'm new to Unity programming. I am trying to build a small RTS. But I have found a problem that I can't solve. The camera moves by itself when it is at its highest point. Can somebody help me.
    Here I leave my code:
    (Thank you very much!!!)


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CameraController2 : MonoBehaviour
    6. {
    7.     public float panSpeed = 100f;
    8.     public float panBorderThickness = 10f;
    9.     public Vector2 panLimit;
    10.  
    11.     public float scrollSpeed = 20f;
    12.     public float minY = 20f;
    13.     public float maxY = 120f;
    14.     public AnimationCurve[] Liac;
    15.  
    16.     public float scroll
    17.     {
    18.         get { return _scroll; }
    19.         set { _scroll = Mathf.Clamp(value, 0, 1); }
    20.  
    21.     }
    22.     float _scroll;
    23.  
    24.  
    25.     // Update is called once per frame
    26.     void Update()
    27.     {
    28.         if (Input.GetMouseButton(2))
    29.         {
    30.             Cursor.lockState = CursorLockMode.Confined;
    31.             Cursor.visible = false;
    32.         }
    33.         else
    34.         {
    35.             Cursor.lockState = CursorLockMode.None;
    36.             Cursor.visible = true;
    37.         }
    38.         Vector3 cameraPosition = transform.position;
    39.         if (Input.GetKey("w") || (Input.mousePosition.y >= Screen.height - panBorderThickness && Input.GetMouseButton(2)))
    40.         {
    41.             cameraPosition.z += panSpeed * Time.deltaTime;
    42.         }
    43.         if (Input.GetKey("s") || (Input.mousePosition.y <= panBorderThickness && Input.GetMouseButton(2)))
    44.         {
    45.             cameraPosition.z -= panSpeed * Time.deltaTime;
    46.         }
    47.         if (Input.GetKey("d") || (Input.mousePosition.x >= Screen.width - panBorderThickness && Input.GetMouseButton(2)))
    48.         {
    49.             cameraPosition.x += panSpeed * Time.deltaTime;
    50.         }
    51.         if (Input.GetKey("a") || (Input.mousePosition.x <= Screen.height - panBorderThickness && Input.GetMouseButton(2)))
    52.         {
    53.             cameraPosition.x -= panSpeed * Time.deltaTime;
    54.         }
    55.  
    56.         scroll += Time.deltaTime * scrollSpeed * Input.GetAxis("Mouse ScrollWheel");
    57.         //Debug.Log(scroll);
    58.  
    59.         RaycastHit rgHit;
    60.         if (Physics.Raycast(transform.position, Vector3.down, out rgHit))
    61.         {
    62.             Liac[0].keys[0].value = minY + rgHit.point.y;
    63.             Liac[0].keys[1].value = maxY + rgHit.point.y;
    64.         }
    65.         cameraPosition.y = Liac[0].Evaluate(scroll);
    66.         cameraPosition.z += Liac[1].Evaluate(scroll) * Time.deltaTime;
    67.  
    68.         transform.eulerAngles = new Vector3(Liac[2].Evaluate(scroll), transform.eulerAngles.y, transform.eulerAngles.z);
    69.  
    70.         cameraPosition.x = Mathf.Clamp(cameraPosition.x, -panLimit.x, panLimit.x);
    71.         cameraPosition.y = Mathf.Clamp(cameraPosition.y, minY, maxY);
    72.         cameraPosition.z = Mathf.Clamp(cameraPosition.z, -panLimit.y, panLimit.y);
    73.        
    74.  
    75.  
    76.         transform.position = cameraPosition;
    77.        
    78.          Debug.Log("Posicion camera " + transform.position);
    79.     }
    80. }
    81.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,945
    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/

    If you insist on wrangling your own, then welcome to debugging! Here's how to get started:

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

    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 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.

    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/

    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)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
     
    AnimalMan likes this.
  3. 3dartmike

    3dartmike

    Joined:
    Apr 1, 2020
    Posts:
    13
    Hello Kurt-Dekker, thank you very much for all that information. Actually I have added a debug.log in the code and it shows me in the console that the camera moves by itself without touching the keyboard.
    My project is for PC, it is not for mobile phones. If you look at the code I use the W, A, S, D keys to move the camera.
    Without pressing these keys the camera moves slightly on its own in the Z axis.
    My question would be how can I make it not move if I am not pressing the W and S keys, which are the ones that control this movement. Excuse my ignorance. I've been studying Unity and C# for just a few months.
     
  4. AnimalMan

    AnimalMan

    Joined:
    Apr 1, 2018
    Posts:
    1,164
    Line

    65 and 66, 70, 71 and 72 are your culprits for modifying camera position outside of input parameters.
     
  5. 3dartmike

    3dartmike

    Joined:
    Apr 1, 2020
    Posts:
    13
    Thanks AnimalMan, it's the cameraPosition.z parameter that gives me problems, I can't understand why if I'm not pressing the "W" and "S" keys, the camera moves slowly along the Z axis when it's at its highest point.
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,945
    That just means you didn't print out the values going into the movement.

    I'm sure when you do you will see that those values are not zero.
     
    AnimalMan likes this.
  7. AnimalMan

    AnimalMan

    Joined:
    Apr 1, 2018
    Posts:
    1,164
    Kurt is correct and Kurt has been programming for at least, since or > 10 years. It may look like a wall of text that is easy to scroll by and ignore but his number one rule, and I have seen it thousands of times before.

    When in doubt; print it out!
    When the Math’s a slog he once said,
    Debug.Log!

    Now knowing the values you’re working with can make a mess of your code! But once you know that they are correct you can be sure of yourself that you’ll never have to look at them again.
     
  8. 3dartmike

    3dartmike

    Joined:
    Apr 1, 2020
    Posts:
    13
  9. 3dartmike

    3dartmike

    Joined:
    Apr 1, 2020
    Posts:
    13
    If I agree, you have to print the values to see what is happening. I accept any advice. I'm learning, so it's normal to feel the whip that sounds
     
  10. 3dartmike

    3dartmike

    Joined:
    Apr 1, 2020
    Posts:
    13
    AnimalMan likes this.