I tried adding a double jump, however the amount of height gained from the double jump changes depending on the time you jump. How do I fix this?
Code:
extends CharacterBody2D
@export var speed = 500
@export var gravity = 100
var Double_Jump = false
@onready var Tim = get_node("Timer")
func _physics_process(delta: float) -> void:
var input_dir = Input.get_axis("Left","Right")
if is_on_floor():
Double_Jump = false
if not is_on_floor():
velocity.y -= gravity
if Double_Jump == true && Input.is_action_just_pressed("Jump"):
print("yay")
velocity.y += -200
else:
if Input.is_action_pressed("Jump"):
velocity.y += -400
Tim.start()
velocity.x = input_dir * speed
move_and_slide()
func _on_timer_timeout() -> void:
print("done")
Double_Jump = true
The problem seems to be that double jump velocity is added to the original vertical velocity. Thus, when original velocity is maximum, more velocity is added to it, making a really high jump. But when original velocity is very less, adding velocity to it makes little difference to the net velocity.
So, in short, your net velocity depends on your original velocity before double jumping, which is constantly varying due to gravity. Since original velocity is always varying, net velocity is always varying, therefore, height is also varying.
To fix this instead of adding velocity to the original velocity, you can assign a specific value to velocity.y while double jumping.
TL;DR:
Change this code:
if Double_Jump == true && Input.is_action_just_pressed("Jump"):
print("yay")
velocity.y += -200
To this code
if Double_Jump == true && Input.is_action_just_pressed("Jump"):
print("yay")
velocity.y = -20 #Change this number according to your needs