Precise jump calculation for given jump height and duration (KinematicBody2D)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Ruszard

Hello,

I’m trying to make my character jumps configurable, where you can define jump height and duration. I’ve checked numerous tutorials about that but the calculations shown there don’t seem to be accurate.

For example i configured my jump height to be 200px but after checking it ingame it appears to be a bit lower (~188px).
I am not sure if the math formula is inaccurate or maybe i am not taking some of the settings into consideration?

Tracked height debug values:

My example code:

extends KinematicBody2D

# Configuration Variables
var jump_height = 200
var jump_duration = 0.3

# Helper Variables
var current_velocity = Vector2()
var gravity
var jump_velocity

# Debug Variables
var highestposition = 0
var initialposition

func _ready():
	gravity = 2 * jump_height / pow(jump_duration, 2)
	jump_velocity = -sqrt(2 * gravity * jump_height)

	# DEBUG - Save original jump position
	initialposition = get_position().y

func _physics_process(delta):
	current_velocity.y += gravity * delta
	current_velocity = move_and_slide(current_velocity, Vector2(0, -1))
	
	# DEBUG - Track the peak position
	var currentpos = initialposition - get_position().y
	if currentpos > highestposition:
		print(currentpos)
		highestposition = currentpos

func _input(event):
	if event.is_action_pressed("jump"):
		current_velocity.y = jump_velocity

		# DEBUG - Reset peak position
		highestposition = 0

Any help would be appreciated

I did a small modification - swapped lines in _physics_process()

current_velocity = move_and_slide(current_velocity, Vector2(0, -1))
current_velocity.y += gravity * delta

And now it overshoots it by reaching 210px jump height.
Console output showing that jump reaches circa 210px of jump height

And i noticed that when you make jump duration longer, it becomes more accurate.

For example for jump that peaks after 1 second:
enter image description here

And for 2 seconds:
enter image description here

Ruszard | 2019-02-24 10:06