Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Simple first person camera script?

Discussion in 'Scripting' started by Soul_Eater301, Jul 22, 2016.

Thread Status:
Not open for further replies.
  1. Soul_Eater301

    Soul_Eater301

    Joined:
    Jun 5, 2016
    Posts:
    5
    Hello Community,
    first of all:
    i look for an simple answer, it does not need to be perfect, but it should be simple and easy to understand for somebody new like me

    Now here is my question:
    Im making a 3D space game, and before i do anything i need my players to be able to look around.
    Because this is in space and the players have jetpacks, the players body should rotate with EVERY mouse movement, that means it rotates around x and y at the same time.
    Here is my problem:
    I know how to make it so the camera turns around x / y axis but not both, and i need a script that is simple and handles both in one camera.
    I currently use transform.Rotate, this works fine for y and x axis on their own, but when i do both together, and move the camera around x and y at the same time (ingame) it will start rotating weirdly.
    Thanks in advance and again i need:
    -simple code
    -in one script bound to the cam
    -that moves in every direction without weird tilting
     
    Ambi_ and Azianus like this.
  2. AndrewTheLeet

    AndrewTheLeet

    Joined:
    Jul 16, 2016
    Posts:
    6
    Ambi_ likes this.
  3. Soul_Eater301

    Soul_Eater301

    Joined:
    Jun 5, 2016
    Posts:
    5
    Thank you for your answer, but it does not seem to work for me. Also its difficult to understand because there is no comment at all in this script so i dont know whats going on
     
    kilopv likes this.
  4. AndrewTheLeet

    AndrewTheLeet

    Joined:
    Jul 16, 2016
    Posts:
    6
    I put in some comments to help you understand it better :)

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. [AddComponentMenu("Camera-Control/Smooth Mouse Look")]
    5. public class SmoothMouseLook : MonoBehaviour {
    6.  
    7.     public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
    8.     public RotationAxes axes = RotationAxes.MouseXAndY;
    9.     public float sensitivityX = 15F;
    10.     public float sensitivityY = 15F;
    11.     public float minimumX = -360F;
    12.     public float maximumX = 360F;
    13.     public float minimumY = -60F;
    14.     public float maximumY = 60F;
    15.     float rotationX = 0F;
    16.     float rotationY = 0F;
    17.     private List<float> rotArrayX = new List<float>();
    18.     float rotAverageX = 0F;
    19.     private List<float> rotArrayY = new List<float>();
    20.     float rotAverageY = 0F;
    21.     public float frameCounter = 20;
    22.     Quaternion originalRotation;
    23.     void Update ()
    24.     {
    25.         if (axes == RotationAxes.MouseXAndY)
    26.         {
    27.             //Resets the average rotation
    28.             rotAverageY = 0f;
    29.             rotAverageX = 0f;
    30.        
    31.             //Gets rotational input from the mouse
    32.             rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
    33.             rotationX += Input.GetAxis("Mouse X") * sensitivityX;
    34.        
    35.             //Adds the rotation values to their relative array
    36.             rotArrayY.Add(rotationY);
    37.             rotArrayX.Add(rotationX);
    38.        
    39.             //If the arrays length is bigger or equal to the value of frameCounter remove the first value in the array
    40.             if (rotArrayY.Count >= frameCounter) {
    41.                 rotArrayY.RemoveAt(0);
    42.             }
    43.             if (rotArrayX.Count >= frameCounter) {
    44.                 rotArrayX.RemoveAt(0);
    45.             }
    46.        
    47.             //Adding up all the rotational input values from each array
    48.             for(int j = 0; j < rotArrayY.Count; j++) {
    49.                 rotAverageY += rotArrayY[j];
    50.             }
    51.             for(int i = 0; i < rotArrayX.Count; i++) {
    52.                 rotAverageX += rotArrayX[i];
    53.             }
    54.        
    55.             //Standard maths to find the average
    56.             rotAverageY /= rotArrayY.Count;
    57.             rotAverageX /= rotArrayX.Count;
    58.        
    59.             //Clamp the rotation average to be within a specific value range
    60.             rotAverageY = ClampAngle (rotAverageY, minimumY, maximumY);
    61.             rotAverageX = ClampAngle (rotAverageX, minimumX, maximumX);
    62.        
    63.             //Get the rotation you will be at next as a Quaternion
    64.             Quaternion yQuaternion = Quaternion.AngleAxis (rotAverageY, Vector3.left);
    65.             Quaternion xQuaternion = Quaternion.AngleAxis (rotAverageX, Vector3.up);
    66.        
    67.             //Rotate
    68.             transform.localRotation = originalRotation * xQuaternion * yQuaternion;
    69.         }
    70.         else if (axes == RotationAxes.MouseX)
    71.         {        
    72.             rotAverageX = 0f;
    73.             rotationX += Input.GetAxis("Mouse X") * sensitivityX;
    74.             rotArrayX.Add(rotationX);
    75.             if (rotArrayX.Count >= frameCounter) {
    76.                 rotArrayX.RemoveAt(0);
    77.             }
    78.             for(int i = 0; i < rotArrayX.Count; i++) {
    79.                 rotAverageX += rotArrayX[i];
    80.             }
    81.             rotAverageX /= rotArrayX.Count;
    82.             rotAverageX = ClampAngle (rotAverageX, minimumX, maximumX);
    83.             Quaternion xQuaternion = Quaternion.AngleAxis (rotAverageX, Vector3.up);
    84.             transform.localRotation = originalRotation * xQuaternion;        
    85.         }
    86.         else
    87.         {        
    88.             rotAverageY = 0f;
    89.             rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
    90.             rotArrayY.Add(rotationY);
    91.             if (rotArrayY.Count >= frameCounter) {
    92.                 rotArrayY.RemoveAt(0);
    93.             }
    94.             for(int j = 0; j < rotArrayY.Count; j++) {
    95.                 rotAverageY += rotArrayY[j];
    96.             }
    97.             rotAverageY /= rotArrayY.Count;
    98.             rotAverageY = ClampAngle (rotAverageY, minimumY, maximumY);
    99.             Quaternion yQuaternion = Quaternion.AngleAxis (rotAverageY, Vector3.left);
    100.             transform.localRotation = originalRotation * yQuaternion;
    101.         }
    102.     }
    103.     void Start ()
    104.     {    
    105.                 Rigidbody rb = GetComponent<Rigidbody>();
    106.         if (rb)
    107.             rb.freezeRotation = true;
    108.         originalRotation = transform.localRotation;
    109.     }
    110.     public static float ClampAngle (float angle, float min, float max)
    111.     {
    112.         angle = angle % 360;
    113.         if ((angle >= -360F) && (angle <= 360F)) {
    114.             if (angle < -360F) {
    115.                 angle += 360F;
    116.             }
    117.             if (angle > 360F) {
    118.                 angle -= 360F;
    119.             }        
    120.         }
    121.         return Mathf.Clamp (angle, min, max);
    122.     }
     
    Last edited: Jul 22, 2016
  5. Soul_Eater301

    Soul_Eater301

    Joined:
    Jun 5, 2016
    Posts:
    5
    First of all: sorry for the slow response and thank you for your comments, but i managed to handle the camera pretty well on my own. but thank you for your work
     
  6. PrMoustache

    PrMoustache

    Joined:
    Jan 3, 2018
    Posts:
    2
    Thanks !
     
  7. taxenmaxen

    taxenmaxen

    Joined:
    Jan 13, 2018
    Posts:
    1
    Thanks !
     
  8. Chamandana

    Chamandana

    Joined:
    Jun 11, 2016
    Posts:
    6
    I know I'm super late, but the When using Input from a specific axis it is good to multiply it from Time.deltaTime and calibrate it. I experienced Ultra high sensitivity in my PC (I've turned down VSync on the editor so it goes like 2000 fps) and in my mobile it is barely impossible to move the camera. :D
     
  9. imdashraful17

    imdashraful17

    Joined:
    Jan 7, 2019
    Posts:
    4
    Why you people working so hard. It is already done in standard assets. Drag first person camera to the view and run your game. So simple
     
    Terrybeh likes this.
  10. Runley

    Runley

    Joined:
    Oct 18, 2018
    Posts:
    1
    cuz people like to make their own scripts, its more rewarding than just drag and drop
     
  11. jamwitk

    jamwitk

    Joined:
    May 16, 2019
    Posts:
    8
    thanks
     
  12. IoMarkou

    IoMarkou

    Joined:
    Dec 1, 2019
    Posts:
    1
    thats 100% true..
     
  13. Fancy_Cat

    Fancy_Cat

    Joined:
    Jan 15, 2020
    Posts:
    1
    Ok idk if anybody still on here but what do i call the cameras script? I named it camera, SmoothMouseLook and still
    have errors. Please help me
     
  14. Snuwiu

    Snuwiu

    Joined:
    Feb 12, 2020
    Posts:
    1
    Maby try to call it CameraRotation or something like that. this should work
     
  15. samcherry2006

    samcherry2006

    Joined:
    Mar 25, 2020
    Posts:
    2
    You have to name it "SmoothMouseLook"
     
  16. samcherry2006

    samcherry2006

    Joined:
    Mar 25, 2020
    Posts:
    2
    Like At the top of the Skript
     
  17. Prella

    Prella

    Joined:
    Mar 11, 2020
    Posts:
    3
    i dont care abput you long script
     
    misticalages likes this.
  18. Prella

    Prella

    Joined:
    Mar 11, 2020
    Posts:
    3
    Please post something simple
     
  19. VillaWolf616

    VillaWolf616

    Joined:
    May 5, 2020
    Posts:
    1
    Lmao you aren't going to learn anything with that attitude. If the idea of a long script is too daunting then maybe programming isn't for you.
     
  20. CZD_Gaming

    CZD_Gaming

    Joined:
    Sep 4, 2020
    Posts:
    3
    Ok but i have seen different scripts but smaller. I am new to c# but there might be some unnecessary parts. For example: he made a float for the clamping but he could have just wrote the number 90 and -90
     
  21. CZD_Gaming

    CZD_Gaming

    Joined:
    Sep 4, 2020
    Posts:
    3
    The frame counter is genius but if you want to go pro you need to multiply but Time.DeltaTime
     
  22. Skyunarankage

    Skyunarankage

    Joined:
    Jun 2, 2017
    Posts:
    10
    What is this overkill?

    Vector3 Angles;
    public float sensitivityX;
    public float sensitivityY;
    void Update()
    {
    float rotationY = Input.GetAxis("Mouse Y")*sensitivityX;
    float rotationX = Input.GetAxis("Mouse X")*sensitivityY;
    if(rotationY>0)
    Angles = new Vector3(Mathf.MoveTowards(Angles.x, -80, rotationY), Angles.y + rotationX, 0);
    else
    Angles = new Vector3(Mathf.MoveTowards(Angles.x, 80, -rotationY), Angles.y + rotationX, 0);
    transform.localEulerAngles = Angles;
    }
     
  23. shipwreckjackson

    shipwreckjackson

    Joined:
    Nov 23, 2020
    Posts:
    3
     
  24. shipwreckjackson

    shipwreckjackson

    Joined:
    Nov 23, 2020
    Posts:
    3
    i cant do the looking because the return Mathf.Clamp (angle, min, max); it keeps making errors
     
  25. shipwreckjackson

    shipwreckjackson

    Joined:
    Nov 23, 2020
    Posts:
    3
    can you fix that
     
  26. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Please, edit your post instead of posting over and over.

    We need to actually know what the errors are before we can fix them.
     
  27. GoStudios_

    GoStudios_

    Joined:
    Dec 4, 2020
    Posts:
    4
    i have this script on my camera and it works properly but it does not match my fist person player's rotation
    can you provide a additional player game Object slot to match player rotation? thanks:)
     
  28. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    39,357
    Please don't reply to 5-year-old posts with a question containing ZERO information about your problem.

    Instead, create your own new post... it's FREE!

    When you do, here is how to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    Also, please use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/
     
    EdgarMolezgomez likes this.
  29. EthanBradMckinnell

    EthanBradMckinnell

    Joined:
    Nov 29, 2020
    Posts:
    1
    scripts are scripts no matter how large or small. but if your wanting to make a script it is best to keep it as small and structured as possible to ensure it performs well in your game and is easy to debug.
     
  30. TreborYDT

    TreborYDT

    Joined:
    Jun 8, 2021
    Posts:
    1
    I have a problem when trying to write my camera script, it doesn't detect my "Input.AxisX" for some reason the imput isn't detected
     
  31. Johan_Liebert123

    Johan_Liebert123

    Joined:
    Apr 15, 2021
    Posts:
    474
    Just create your own thread, no need to reply to others as Kurt already mentioned.

    You probably typed it wrong, show us your script so we know what you have done wrong
     
  32. Ulezavunje

    Ulezavunje

    Joined:
    Jul 2, 2021
    Posts:
    1
    for anyone who wants to rotate their player with the script(just put your object in the player slot in the inspector, you can also do it to a camera ti get the same effect)

    Vector3 Angles;
    public Transform player;
    public float sensitivityX;
    public float sensitivityY;
    void Update()
    {
    float rotationY = Input.GetAxis("Mouse Y")*sensitivityX;
    player.Rotate(0, Input.GetAxis("Mouse X")*sensitivityY, 0);
    if(rotationY>0)
    {
    Angles = new Vector3(Mathf.MoveTowards(Angles.x, -90, rotationY),0);
    }
    else
    {
    Angles = new Vector3(Mathf.MoveTowards(Angles.x, 90, -rotationY),0);
    transform.localEulerAngles = Angles;
    }
    }
     
    fgw_unity likes this.
Thread Status:
Not open for further replies.