Diagonal jump results with weird motion.

What i want to achieve is the player being able to jump diagonally. using this code kinda works however player jumps more to the y-axis. instead of going x,y(15,15) it jumps more like x,y(5,15) even though xpower is same as the ypower. and if i increase the xpower to 30 or more. it starts off by going left or right incredibly fast for a brief second before even starting to go upwards.

GetAxis(“Horizontal_LRUD”) will return between -1,1 depending on the left right input.

private Rigidbody2D rg2d;

void Start()
{
    rg2d = GetComponent<Rigidbody2D>();
}

void Update()
{
    if (Input.GetAxis("Horizontal_LRUD") != 0f)
    {
        rg2d.velocity = new Vector2(Input.GetAxis("Horizontal_LRUD") * 5, rg2d.velocity.y);
    }

    if (Input.GetKeyDown(KeyCode.A))
    {
        int xpower = 15, ypower = 15;

        rg2d.velocity = new Vector2(Input.GetAxis("Horizontal_LRUD") * xpower, ypower);
    }
}

It’s pretty simple, you erase the previous horizontal velocity every frame, therefore your horizontal jump only works for one frame.

To fix this, you need to check if you are currently in the air, and if so, keep the previous horizontal velocity.


The problem will be a lack of control mid-air, which is usually not user-friendly. You can reduce that by instead using mid-air acceleration. Basically instead of replacing the previous velocity, you increment it every frame by the current input.

velocity += Input.GetAxisRaw("Horizontal_LRUD") * airAcceleration * Time.deltaTime;

velocity.x = Mathf.Clamp(rg2d.velocity.x, -maxAirSpeed, maxAirSpeed);

Please note that because this is in Update, you will get slightly different results depending on Framerate.