Search Unity

Need help making a camera script

Discussion in 'Scripting' started by Jonhas, Sep 19, 2019.

  1. Jonhas

    Jonhas

    Joined:
    Jul 28, 2019
    Posts:
    46


    This is a short question, how can I improve the camera script, I do not need a wiki page about, just edit the piece of code as I have seen it (and it is way too complicated for me to understand).

    Code (CSharp):
    1.         if (CamX < 0)
    2.         {
    3.             Camera.transform.Rotate(0, -1, 0);
    4.         }
    5.         if (CamX > 0)
    6.         {
    7.             Camera.transform.Rotate(0, 1, 0);
    8.         }
    9.         if (CamY > 0)
    10.         {
    11.             Camera.transform.Rotate(-1, 0, 0);
    12.         }
    13.         if (CamY < 0)
    14.         {
    15.             Camera.transform.Rotate(1, 0, 0);
    16.         }
    PS. I know using a bunch of if's is messy, but if I make it else if then it goes messy, you'll know why. Sorry for the laggy video quality if it is like 2 fps, I hope you can tell what is wrong with camera.
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    A way to prevent that from happening is to always set the target rotation, not apply some rotation for every small change. I believe (?) the problem here has to do with the accumulation of small imprecisions or something like that.
    This code should do what you want it to:
    Code (CSharp):
    1. //In Update()
    2. Vector2 mouseInput = new Vector2(Input.GetAxisRaw("Mouse Y"), Input.GetAxisRaw("Mouse X"));
    3. mouseDelta += mouseInput; // mouseDelta being a Vector2 defined outside of Update()
    4. transform.eulerAngles = new Vector3(-mouseDelta.x, mouseDelta.y, 0);
    You may wanna lock the rotation to some range tho.
     
  3. Jonhas

    Jonhas

    Joined:
    Jul 28, 2019
    Posts:
    46
    Thanks a bunch! It still has minor problems but I am sure I can get those fixed.
     
  4. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    I only did quick testings. If you still need help, please tell me/us what problems are left after you tried fixing them.
     
  5. Jonhas

    Jonhas

    Joined:
    Jul 28, 2019
    Posts:
    46
    Alright, I'll be making a thread about some other stuff with the camera unrelated with this just to let you know.