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

I was watching a tutorial to learn the basics and the code isn't working properly.

Discussion in 'Getting Started' started by Y0urNameHere, Sep 21, 2023.

  1. Y0urNameHere

    Y0urNameHere

    Joined:
    Sep 20, 2023
    Posts:
    1
    So im trying to make my character look around, since I don't know much about the engine I went to watch a tutorial to try see how things were done but the code isn't working right idk if it's because of any update but what is happening is: when I look left and right my character moves along in that direction while I want him to rotate in the direction that I was looking at.

    Here is the code:
    Code (CSharp):
    1. //mouse sense
    2. public float mousesense = 100f;
    3.  
    4. //player body
    5. public Transform body;
    6.  
    7.  
    8. float xrotation = 0f;
    9.  
    10. // Start is called before the first frame update
    11. void Start()
    12. {
    13.     Cursor.lockState = CursorLockMode.Locked;
    14. }
    15.  
    16. // Update is called once per frame
    17. void Update()
    18. {
    19.     //get mouse x and y axis
    20.     float mouseX = Input.GetAxis("Mouse X") * mousesense * Time.deltaTime;
    21.     float mouseY = Input.GetAxis("Mouse Y") * mousesense * Time.deltaTime;
    22.  
    23.     xrotation -= mouseY;
    24.     xrotation = Mathf.Clamp(xrotation, -90f, 90f);
    25.  
    26.     transform.localRotation = Quaternion.Euler(xrotation, 0f, 0f);
    27.  
    28.     //rotate player with mouse
    29.     body.Rotate(Vector3.up * mouseX);
    30. }
     
  2. whoft

    whoft

    Joined:
    Jul 1, 2021
    Posts:
    17
    First of all: Why is your mouse input being multiplied by Time.deltaTime? Would you mind sharing your tutorial, because this doesn't make any sense.
    Next, your code seems to defeat its own purpose, by calling
    Code (CSharp):
    1. body.Rotate(Vector3.up * mouseX);
    after properly rotating your character on the X axis by rotating it again.

    Can you link your tutorial? I can't seem to make heads or tails of this code.
     
  3. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,860
    Yeah, this is a train wreck and it's likely not your fault but the tutorial author. It would be interesting to see this tutorial.