Make Player move based on key input

So, this should be a very basic thing to do, all of the other key inputs in this script works, but for some reason, this key input does not. Anyone know why

using System.Collections; /*We are using the "using" keyword to signify that we are implementing the Collections class of the System package(because
unity can not use Generic as a baselayer for a script) in this scope/file*/
using System.Collections.Generic; /*We are using the "using" keyword to signify that we are implementing the Generic class of the System.Collections
package(because it contains generic class definition and provides you to better type safly) in this scope/file*/
using UnityEngine; /*We are using the "using" keyword to signify that we are implementing the UnityEngine class(because it allows us to use all of
unity class definitions, keywords, default method and everythine) in this scope/file*/

public class PlayerMovementE5 : MonoBehaviour /*Creates a public(which means it's accesible to every other file) with the name
"PlayerMovementE5" that imports it with the baseclass of "MonoBehaviour"(which means it can be attached to a gameobjct)*/
{

    public Rigidbody rb; /*Creates a public(which means it can be accesed by either the inspectoor-if thsscript is attached to a object-or to
    another script if that script imprts this file) using the Rigidbody keyword(which is a component that can be attached to a gameobject)
    nicknamed "rb"*/

    public Vector3 jump;
    public float moveForward = 200f; /*Creates a public(meaning it can be changed via the inspector and called in other scripts) float(meaning it can have de
    cimals) nicknamed "moveForward" that has a value of 200*/
    public float moveBackward = -200f;/*Creates a public(meaning it can be changed via the inspector and called in other scripts) float(meaning it can have de
    cimals) nicknamed "moveBakward" that has a value of -200*/
    public float moveLeft = -150f;/*Creates a public(meaning it can be changed via the inspector and called in other scripts) float(meaning it can have de
    cimals) nicknamed "moveLeft" that has a value of -150*/
    public float moveRight = 150f; /*Creates a public(meaning it can be changed via the inspector and called in other scripts) float(meaning it can have de
    cimals) nicknamed "moveRight" that has a value of 150*/
    public float moveUp = 1.0f;
    public float maxSpeed = 20f;
    public float minSpeed = 0f;
    public float currentForwardSpeed;
    public float currentBackwardSpeed;
    public float currentLeftSpeed;
    public float currentRightSpeed;


    public bool isGrouded;
    void Start() /*Creates a void(Which means it returns nothing) constructor nicknamed with the pre-made Unity Consstructor "Start" and...*/
    {
        //rb.useGravity = false; /*Sets the useGravity on the nicknamed rididdbody 'rb' to false(meaning the gameobject has no gravity)*/
        Debug.Log("I'm floating!! Wheee"); /*Logs a message to the console thatsays whatevers in the paranthesis*/
        jump = new Vector3(0.0f, 1.0f, 0.0f);
    }

    void OnCollisionStay() {
         isGrouded = true;
    }

    // Update is called once per frame
    void Update() /*Creates a void(Which means it returns nothing) constructor nicknamed with the pre-made Unity Consstructor "Update" and...*/
    {
        if(Input.GetKeyDown(KeyCode.Space) && isGrouded) {
            rb.AddForce(jump * moveUp, ForceMode.Impulse);
            isGrouded = false;
        }
    }

    void FixedUpdate() { /*Creates a void(Which means it returns nothing) constructor nicknamed with the pre-made Unity Consstructor "FixedUpdate",
    and...*/
            currentForwardSpeed = moveForward * Time.deltaTime; /*Make the nicknamed float "currentForwardSpeed" equal to the icknamed float
           "moveForward" multiplied by Time.deltaTime)*/
            currentForwardSpeed = Mathf.Clamp(moveForward, minSpeed, maxSpeed);
            rb.velocity = new Vector3(rb.velocity.x, rb.velocity.y, (currentForwardSpeed));

        if(Input.GetKey("s")) { /*Passes the "s" button as an arguement in the GetKey method of the Input class as the if condition(meaning if s
         gets pressed) and...*/
                currentBackwardSpeed = moveBackward * Time.deltaTime;
                currentBackwardSpeed = Mathf.Clamp(moveBackward, minSpeed, maxSpeed);

                rb.velocity = new Vector3(rb.velocity.x, rb.velocity.y, (currentBackwardSpeed));       
          }

        if(Input.GetKey("d")) { /*Passes the "d" button as an arguement in the GetKey method of the Input class as the if condition(meaning if d
         gets pressed) and...*/
                currentRightSpeed = moveRight * Time.deltaTime;
                currentRightSpeed = Mathf.Clamp(moveRight, minSpeed, maxSpeed);

                rb.velocity = new Vector3((currentRightSpeed), rb.velocity.y, rb.velocity.z);
        }

        if(Input.GetKey("a")) { /*Passes the "s" button as an arguement in the GetKey method of the Input class as the if condition(meaning if s
         gets pressed) and...*/
             currentLeftSpeed = moveLeft * Time.deltaTime;
             currentLeftSpeed = Mathf.Clamp(moveLeft, minSpeed, maxSpeed);

             rb.velocity = new Vector3((currentLeftSpeed), rb.velocity.y, rb.velocity.z);
        }

        if(rb.position.y < -250f) { /*Gets the variable nicknamed "rb" and get the y value and see if its has a y value of less than -100 then...*/
            FindObjectOfType<GameManagerE5>().EndGame(); /*Findthe game object "GameManagerE5" and uses it's method "EndGame""*/
        }
    }
}

and if you’re wondering why I’m not useing rb.AddForce() is because rb.AddForce() gradually speeds up the player throughout the game and I want the speed to remain constant

*EDIT: I just relized I did not say what key input isnt working, its a

If you’re using AddForce() and also setting the velocity directly, only one is going to prevail, which ever is the latest one.

There’s also quite a lot of tangle and duplicated copy/pasta code for just moving a player… you might want to break it out into steps, clean it up a bit:

  • make a Vector3 movement variable at the top of the FixedUpdate(), set it to zero
  • test each key direction, set the X or Y component of the movement appropriately
  • when all key testing is done, scale up the X and Y in movment
  • set that movement variable to your rb.velocity

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

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 put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

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.

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:

OK, what is up with those code comments? That’s the worst documentation I’ve ever seen, it’s literally just typing the code again using more words. That’s not your problem here obviously, but it really bugs me. If not for the typos in it or the things that are just flat wrong (FixedUpdate isn’t a constructor) I would say it looks like it was a tool that autogenerates code comments to try and help you understand coding basics…? And then to make it worse it uses /* block comment syntax */ for single-line comments instead of // line comments and just makes the entire script look insanely cluttered…

Anyway, you’re correct that this should be a basic thing, and you’ve made a big complicated function by not taking advantage of the tools Unity has for just this purpose. Rather than checking for each key individually, you should really be using Input.GetAxis, which will give you a number -1.0 to 1.0 for left to right (with 0.0 being no input) (or down to up). The axes are configured in project settings → Input and the default Unity project includes Horizontal and Vertical (capitalization must match) which are set up to accept joystick, arrows, and WADS controls. So use this instead of your big set of if statements, and you’ll get two simple numbers that you can just multiply by a speed value and plug straight into your velocity.

Another issue you’re having is multiplying Time.deltaTime into your speed. If you’re applying movement to the position directly that is the correct thing to do, but you’re applying it to velocity. This being run from FixedUpdate, where deltaTime is always at 0.02 by default, you’re basically dividing the intended speed by 50. I wonder if this is the main reason it appears to not be working - you’re making it 50x slower with this mistake.

There’s also a problem with your Clamping. You have negative numbers for your left and backward movement, which is correct, but then you clamp those numbers to between 0 and 20, so your negative number is getting clamped to 0. So left and backward won’t move at all for this reason, while your other direction are probably moving 50x slower than normal due to the deltaTime mistake. Since you’re using physics you may also be running into friction which could slow that 50x slower movement to 0 easily.

1 Like