Making the player control 3 positions using left and right arrow keys.

Hey everyone,

I’m just starting out with Unity/scripting and have something I need help with.

To start out with my first project I simply want to be able to do the following:

  • There’s a sprite (the player) in the center of the screen.
  • When you hold the right arrow the sprite moves to a static position on the right side of the screen.
  • When you hold the left arrow the sprite moves to a static position on the left side of the screen.
  • When neither of the keys is being held, the sprite moves back to it’s original position in the center.
  • Like this:

This is what I have so far. (Trying to get it working in the console)

void centerChecker () {
        if (!Input.GetKey ("right") || !Input.GetKey ("left"))
            print ("CENTER");
    }

    void Update () {
        if (Input.GetKey ("left")) {
            print ("SPRITE TO LEFT");
        }
        if (Input.GetKey ("right")) {
            print ("SPRITE TO RIGHT.");
        }
   
        centerChecker ();
    }

The problem is that instead of just printing “SPRITE TO RIGHT/LEFT” when an arrow key is held, it also keeps printing “CENTER”. When I remove "|| !Input.GetKey (“left”)" from the if condition in the centerChecker function it works exactly how I want it to work, but only for the right side. I’ve already tried using to seperate functions to check the left and the right side independantly but I can’t get it to work.

Any help would be greatly appreciated.

Your if statement has a logical error. You are saying to print center if the right key is not being pressed or the left key is not being pressed. So if EITHER key is not being pressed it will print ‘CENTER’. You want if BOTH are not being pressed. Just change the or to an and. So ‘||’ becomes ‘&&’.

That actually makes a lot of sense. Tried it out and it worked like a charm. Thanks so much!