Search Unity

Question can someone help me with my code

Discussion in 'Scripting' started by Sleepy054, May 19, 2023.

  1. Sleepy054

    Sleepy054

    Joined:
    May 11, 2023
    Posts:
    6
    I have a the wasd and a mouse look controls but when I use it will fly around anyone know how to fix it and how do I also lock my mouse in place?


    here is the code:
    Code (CSharp):
    1. float shiftAdd = 250.0f; //multiplied by how long shift is held. Basically running
    2. float maxShift = 1000.0f; //Maximum speed when holdin gshift
    3. float camSens = 0.25f; //How sensitive it with mouse
    4. private Vector3 lastMouse = new Vector3(255, 255, 255); //kind of in the middle of the screen, rather than at the top (play)
    5. private float totalRun= 1.0f;
    6.  
    7. void Update () {
    8. lastMouse = Input.mousePosition - lastMouse ;
    9. lastMouse = new Vector3(-lastMouse.y * camSens, lastMouse.x * camSens, 0 );
    10. lastMouse = new Vector3(transform.eulerAngles.x + lastMouse.x , transform.eulerAngles.y + lastMouse.y, 0);
    11. transform.eulerAngles = lastMouse;
    12. lastMouse = Input.mousePosition;
    13. //Mouse camera angle done.
    14.  
    15. //Keyboard commands
    16. float f = 0.0f;
    17. Vector3 p = GetBaseInput();
    18. if (p.sqrMagnitude > 0){ // only move while a direction key is pressed
    19. if (Input.GetKey (KeyCode.LeftShift)){
    20. totalRun += Time.deltaTime;
    21. p = p * totalRun * shiftAdd;
    22. p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
    23. p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
    24. p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
    25. } else {
    26. totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
    27. p = p * mainSpeed;
    28. }
    29.  
    30. p = p * Time.deltaTime;
    31. Vector3 newPosition = transform.position;
    32. if (Input.GetKey(KeyCode.Space)){ //If player wants to move on X and Z axis only
    33. transform.Translate(p);
    34. newPosition.x = transform.position.x;
    35. newPosition.z = transform.position.z;
    36. transform.position = newPosition;
    37. } else {
    38. transform.Translate(p);
    39. }
    40. }
    41. }
    42.  
    43. private Vector3 GetBaseInput() { //returns the basic values, if it's 0 than it's not active.
    44. Vector3 p_Velocity = new Vector3();
    45. if (Input.GetKey (KeyCode.W)){
    46. p_Velocity += new Vector3(0, 0 , 1);
    47. }
    48. if (Input.GetKey (KeyCode.S)){
    49. p_Velocity += new Vector3(0, 0, -1);
    50. }
    51. if (Input.GetKey (KeyCode.A)){
    52. p_Velocity += new Vector3(-1, 0, 0);
    53. }
    54. if (Input.GetKey (KeyCode.D)){
    55. p_Velocity += new Vector3(1, 0, 0);
    56. }
    57. return p_Velocity;
    58. }
    59. }
    60. float mainSpeed = 100.0f; //regular speed
     
    Last edited: May 19, 2023
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    Please use code tags to post code in a readable format.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    How to report your problem productively in the Unity3D forums:

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

    This is the bare minimum of information to report:

    - what you want
    - what you tried
    - what you expected to happen
    - what actually happened, log output, variable values, and especially any errors you see
    - links to documentation you used to cross-check your work (CRITICAL!!!)

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    If you have a problem with how your program actually runs 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.
     
  4. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    Lets get this into code tags using the instructions from the pinned thread:
    https://forum.unity.com/threads/using-code-tags-properly.143875/

    Code (csharp):
    1.     float shiftAdd = 250.0f; //multiplied by how long shift is held. Basically running
    2.     float maxShift = 1000.0f; //Maximum speed when holdin gshift
    3.     float camSens = 0.25f; //How sensitive it with mouse
    4.     private Vector3 lastMouse = new Vector3(255, 255, 255); //kind of in the middle of the screen, rather than at the top (play)
    5.     private float totalRun= 1.0f;
    6.  
    7.     void Update () {
    8.         lastMouse = Input.mousePosition - lastMouse ;
    9.         lastMouse = new Vector3(-lastMouse.y * camSens, lastMouse.x * camSens, 0 );
    10.         lastMouse = new Vector3(transform.eulerAngles.x + lastMouse.x , transform.eulerAngles.y + lastMouse.y, 0);
    11.         transform.eulerAngles = lastMouse;
    12.         lastMouse = Input.mousePosition;
    13.         //Mouse camera angle done.
    14.  
    15.         //Keyboard commands
    16.         float f = 0.0f;
    17.         Vector3 p = GetBaseInput();
    18.         if (p.sqrMagnitude > 0){ // only move while a direction key is pressed
    19.             if (Input.GetKey (KeyCode.LeftShift)){
    20.                 totalRun += Time.deltaTime;
    21.                 p = p * totalRun * shiftAdd;
    22.                 p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
    23.                 p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
    24.                 p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
    25.             } else {
    26.                 totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
    27.                 p = p * mainSpeed;
    28.             }
    29.  
    30.             p = p * Time.deltaTime;
    31.             Vector3 newPosition = transform.position;
    32.             if (Input.GetKey(KeyCode.Space)){ //If player wants to move on X and Z axis only
    33.                 transform.Translate(p);
    34.                 newPosition.x = transform.position.x;
    35.                 newPosition.z = transform.position.z;
    36.                 transform.position = newPosition;
    37.             } else {
    38.                 transform.Translate(p);
    39.             }
    40.         }
    41.     }
    42.  
    43.     private Vector3 GetBaseInput() { //returns the basic values, if it's 0 than it's not active.
    44.         Vector3 p_Velocity = new Vector3();
    45.         if (Input.GetKey (KeyCode.W)){
    46.             p_Velocity += new Vector3(0, 0 , 1);
    47.         }
    48.         if (Input.GetKey (KeyCode.S)){
    49.             p_Velocity += new Vector3(0, 0, -1);
    50.         }
    51.         if (Input.GetKey (KeyCode.A)){
    52.             p_Velocity += new Vector3(-1, 0, 0);
    53.         }
    54.         if (Input.GetKey (KeyCode.D)){
    55.             p_Velocity += new Vector3(1, 0, 0);
    56.         }
    57.         return p_Velocity;
    58.     }
    59. }
    60. float mainSpeed = 100.0f; //regular speed
    Next, we have some strange code dangling at the end here... but ok.

    On to your questions:
    "when i use it i would fly around" - this is because your code only uses Transform.Translate. There is no gravity anywhere, nor any collision. You should be using a Rigidbody and any of its various methods that move it around (each with its own way of doing that... and the one you pick depends on how you want your controls to feel). Or you can use a CharacterController and the 'Move' method on that.

    "how do i also lock my mouse in place" - use the Cursor.lockState if you want to lock it:
    https://docs.unity3d.com/ScriptReference/Cursor-lockState.html

    ...

    If you desire more in depth assistance than that you should attempt to post a more coherent post with code formatted correctly. Also toss in some level of grammar and punctuation... doesn't have to be perfect, mine is far from, but something... a capital letter at the beginning of your sentences would be a nice first step.
     
  5. Sleepy054

    Sleepy054

    Joined:
    May 11, 2023
    Posts:
    6
    thank you also do i have to make a new scrip so i can put mouse lock?
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    You can do everything in one script, you can make 27,000 scripts.

    Generally speaking a script should have a single area of responsibility.

    https://en.wikipedia.org/wiki/Single-responsibility_principle

    Otherwise, if you just need a good basic first person character controller and don't care about the noodly details, here's one:

    https://forum.unity.com/threads/a-basic-first-person-character-controller-for-prototyping.1169491/

    That one has run, walk, jump, slide, crouch... it's crazy-nutty!!