How to make top down movement Better

So I’ve been making a new game from scratch, my second ever project. It’s a top-down shooter, and I’ve starting working on the movement of the character but I keep finding it’s not working as well as I thought it would. I’m making it by using if statements and velocity like this.

void Update()
{

    if (Input.GetKey(KeyCode.W))
    {
        playerVelo.y = upwardSpeed;
        myBody.velocity = playerVelo;
        Debug.Log("Up");
    }

    if (Input.GetKey(KeyCode.D))
    {
        playerVelo.x = sideWaySpeed;
        myBody.velocity = playerVelo;
        Debug.Log("Right");
    }

    if (!Input.anyKey)
    {
        playerVelo = new Vector2(0,0);
        myBody.velocity = playerVelo;
        Debug.Log("NothingPressed");
    }

}

But the code has a weird property were if I stop pressing say the D key it should just go up but it doesn’t it keep moving right and up until I stop pressing every button is there any way I can check only if one button goes up, I keep looking it up but I really can’t find anything.

This happens because you set playerVelo.x equal to sideWaySpeed, and that value will not change until you stop pressing any key and reset it with playerVelo = new Vector2(0, 0);. Until then, playerVelo.x keeps the last value you assigned to it.

You could have debugged this yourself by having your logs print the playerVelo vector at the end of each Update instead of printing messages. Using Debug.Log to output variable values rather than text messages is a better debugging habit.

For a more general solution, you need to understand that Unity does not execute instructions the moment we write them. We are operating inside its game loop. What we are really doing is telling Unity: when it is time to update the physics, set the velocity of mBody to whatever value was last assigned.

You are changing now physics properties in Update, which runs at variable intervals. Physics should be handled in FixedUpdate, which runs at consistent steps. Try this approach instead:

In Update, use a vector to represent the player’s intended velocity and always initialize it to zero:
playerVelo = new Vector2(0, 0);

Then, depending on which keys are pressed, add to that vector the movement direction. For example:
playerVelo = playerVelo + new Vector2(0, 1);

Finally, in FixedUpdate, set the rigidbody’s velocity equal to playerVelo.

This way, the final movement vector is the sum of all the input directions (or zero if no keys are pressed), and the rigidbody is only updated during the physics step.

This still needs a minor fix, normalize the vector so the character won’t move faster when moving diagonally.

As @meredoth points out, you need slightly different logic.

I use the structure meredoth mentions all the time, with some slight changes.

This would be how I do it:

  Vector2 movement = Vector2.zero;

  // read keyboard keys
  if (Input.GetKey(KeyCode.LeftArrow)) movement.x = -1;
  // etc for up, right, down

  // Read joysticks ... put joystick reading here

  // read touchscreen joysticks - put touchscreen reading here

  // optional: circularize the input by normalizing it (so diagonal is the same speed)
  movement.Normalize();

  // now scale it up by walk speed (a floating point number)
  movement *= WalkSpeed;

  // now finally set the player Rigidbody to the movement here
  myRigidbody.velocity = movement;

This lets you jam in other control input sources trivially.

Assuming all input sources are from -1 to 0 to +1, then all of them are scaled by WalkSpeed and you have harmony among your input types.

That’s the way you coded it. :wink:

if (!Input.anyKey)
    {
        playerVelo = new Vector2(0,0);
        myBody.velocity = playerVelo;
        Debug.Log("NothingPressed");
    }

This reads: If (and only if) no key is pressed will the player stop.

You actually want to chain these conditions:

if (W) => up
else if (D) => right
else => stop

This reads: If neither W nor D are pressed, then stop.

Still not ideal since scaling this if/else if/else chain with multiple inputs becomes a real nuisance and source of further bugs once you get past 4-6 input actions.

One more thing: never repeat any condition in an if/else if/else chain:

if (a)
else if (!a && b)
else if (!a && !b)

Follow the logic. You’ll notice !a and !a && !b are superfluous. It’s the same as:

if (a)
else if (b) // !a is implied, preceding if(a) handles "a == true" case
else // same implication

Suddenly, much less logic to wrap your head around.
A good IDE will tell you this btw. It de-emphasizes redundant conditions, typically in a color with less constrast. Or some colored underline with a tooltip.

I’ll add one point, since the rest has already been covered well.

There are two ways to approach development: you’re either building a product, or you’re experimenting for fun and learning. Both are valid, but they lead to very different decisions.

For systems and components that exist in nearly every game audio, input, UI, camera, controllers I would usually advise both product developers and hobbyists to use pre-existing assets and integrate them cleanly. Save custom work for the parts that actually differentiate your project, like specific systems that enhance gameplay and have fun doing.

It would’ve been more appropriate to link a 2D controller rather than 3D. The OP is discussing 2D physics etc. Not everything is transferable and can be quite confusing for a beginner. :slight_smile:

That’s just an example of a package.

Sure but a package that isn’t appropriate to the question being posed by the OP which was my point. There’s plenty of 2D related stuff for this.

While I understand your point, there’s only one tag that specifies that it’s 2d-physics, while the code itself doesn’t explicitly define 2D or 3D:

    if (Input.GetKey(KeyCode.D))
    {
        playerVelo.x = sideWaySpeed;
        myBody.velocity = playerVelo;
        Debug.Log("Right");
    }

The “top-down” term only describes the perspective, not whether the game is technically 2D or 3D.

That said, when you write a character controller for 2D, you’re really still just making a 3D controller constrained to 2D movement, even if you’re moving via Rigidbody velocity instead of transform.position. Concepts like Vector3 are still involved under the hood, and there’s no real downside to using a 3D or 2D controller in my opinion here.

If that were a larger concern to me, I would have looked harder for a dedicated 2D controller, but I don’t see any reason a 3D controller wouldn’t work for his use case, and it also was just an example to show a free package on the asset store.

I updated my post to reflect the packages.

If only it was true that 2D is simply 3D but with an extra constraint! That would’ve saved me many thousands of hours implementing 2D physics over the last decade and all the considerably different APIs. :slight_smile:

I do appreciate you updating your link to a more general area.

Thanks!