If you have ever played Super Meat Boy by Edmund McMillen, you must be impressed by one of the interesting mechanisms, the charged jump.
Usually the jump action has a corresponding key binding .When you press the key (for example Space key here), the character will jump with a predefined vertical speed. Charged jump here means a higher jump when you press the key and hold for a while. This mechanism is popular in some 2D adventure games whose gameplay rely majorly on 2D physics.
To realize this, we can try two different ways.
- Slow down the deceleration of the vertical speed affected by gravity with the jump key holded.
- Simple reduce the vertical speed when the jump key is up.
For the first one, we can simply do like this:1
2
3
4
5if (Input.GetButtonDown ("Jump") && grounded) {
velocity.y = jumpTakeOffSpeed;
} else if (Input.GetButton ("Jump")) {
velocity.y *= 1.05f;
}
Result:
For the second one, we can simply do like this:1
2
3
4
5
6
7
8if (Input.GetButtonDown ("Jump") && grounded) {
velocity.y = jumpTakeOffSpeed;
} else if (Input.GetButtonUp ("Jump"))
{
if (velocity.y > 0) {
velocity.y = velocity.y * 0.5f;
}
}
Results:
Comparing these two solutions, i think the latter one should be better. The first one is more like you try to reduce the gravity affect on the character. It’s not easy to control the jump height, and it also slows down the deceleration of the fall down speed. The second one is simpler and easy to control the jump height. Instead of simply half the speed, you can declare a public field called compensation to replace the “0.5f” there.