Cant figure out 2d movement

the code below is supposed to be for a 2d platformer, the horizontal movement works fine but the gravity breaks, causing my character to slowly glide down, I havent yet implemented a groundcheck and if it would work with my current code how would i implement it.

public float moveSpeed;
    public float jumpforce;
    public Rigidbody2D rb;

    // Update is called once per frame
    void Update()
    {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Jump");

        rb.velocity = new Vector2 (moveHorizontal*moveSpeed, moveVertical*jumpforce);

    }

Gravity affects vertical velocity (assuming you’re using the default) but you’re just stomping over the vertical velocity so gravity does nothing. Also note, physics (by default) doesn’t run per-frame, it runs during the FixedUpdate unless you change it.

This is why it’s typical to use forces/impulses which modify the velocity. If you directly modify velocity, you need to know what you’re doing.

There’s a lot of information and tutorials about 2D movement online.

The code above is a simple copy-axes-into-velocities piece of code.

It copies Horizontal into x-motion and Jump (normally never treated as an axis) into y.

That’s all it does. Don’t expect more. You can see the three whole glorious lines of code all at once.

Since it is 2024, as Mel points out there are a LOT of 2D platform movement resources out there. Go do some tutorials for whatever platformer movement flavor you desire.

If you can’t get it from tutorials I guarantee you won’t get it from thie little tiny text box!

Two steps to tutorials and / or example code:

  1. do them perfectly, to the letter (zero typos, including punctuation and capitalization)
  2. stop and understand each step to understand what is going on.

If you go past anything that you don’t understand, then you’re just mimicking what you saw without actually learning, essentially wasting your own time. It’s only two steps. Don’t skip either step.

Imphenzia: How Did I Learn To Make Games:

1 Like