Jump not affected by changing velosity.y

Hello :slight_smile:

I’ve just done double jump in my game and in a some way it’s affected by changing velosity.y by game object. It means the power of second jump depends on a time(?) and changing velosity.y(?) between double clicking “Space”. I want to make it independent and the jump’s power is need to be the same all the time. Where am I wrong?

Thanks in advance!

Tomas

void Update () 
{
	if(Input.GetKeyDown(KeyCode.Space))
	{
		if(grounded)
		{
			rigidbody2D.AddForce(new Vector2(0f, jumpingForce * moving));
			grounded = false;
			jumpCounter = 1;
		}
		else if(!grounded && jumpCounter == 1)
		{
			jumpCounter++;
			rigidbody2D.AddForce(new Vector2(0f, jumpingForce * moving));
			//Debug.LogError("And second jump");
		}

	 }
}

It sounds like you want to be setting the velocity to achieve what you’re after, rather than applying a force.

Let’s say that when your player is grounded, the force you apply is enough to make the player start to move upward at 5m/s. If the player jumps off a cliff, and ends up travelling downwards at high speed, then applying that force again won’t make them switch to moving up at 5m/s, it’ll just slow them down a bit - it takes a bigger force to make a falling object move upwards at that speed than a stationary one. What you want is to just override the vertical speed.

Unfortunately you can’t just set rigidbody2D.velocity.y - this is because Rigidbody2D.velocity is a property rather than a variable and actually returns a COPY of the velocity vector, so then setting .y doesn’t actually affect the rigidbody. Try something like this:

float jumpVelocity=10.0f; //Or whatever is appropriate for your game.
Vector2 currentVelocity=rigidbody2D.velocity;
rigidbody2D.velocity=new Vector2(currentVelocity.x, jumpVelocity);

This will override the current vertical speed with your jumping speed.

This is in line with the (3D) Rigidbody documentation here: Unity - Scripting API: Rigidbody.velocity where setting the velocity directly is generally discouraged, but jumping is noted as a common exception.