how to limit jumps until a surface is touched

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

I am making a metroidvania game and i want to limit how many times the player can jump before colliding. my code is bellow:

extends KinematicBody2D

const GRAVITY = 10 # in pixels
const JUMP = 250 # start speed px/s
const SPEED = 200 # px/s

var velocity = Vector2.ZERO # (0,0)

func _ready():
func _on_Timer_timeout():
	print(str($Timer.wait_time) + " second(s) finished")
func _physics_process(delta):
	# if no keyboard input for left/right then x speed is 0
	velocity.x = 0 
		velocity.x = SPEED
		velocity.x = -SPEED
	velocity.y += GRAVITY
	if (Input.is_action_just_pressed("jump")):
		velocity.y -= 250
	velocity = move_and_slide(velocity)
:bust_in_silhouette: Reply From: CardboardComputers

Well, you can have for example

var jumps_available := 2

at the top of your code, then simply

# _physics_process
if Input.is_action_just_pressed("jump") and jumps_available > 0:
    velocity.y -= 250
    jumps_available -= 1

along with some kind of reset condition, such as

# _physics_process
if is_on_floor():
    jumps_available = 2

and that should give a rudimentary kind of double-jump functionality.

will floor count as any surface?

PopSquip | 2021-08-31 05:01

I don’t know, it depends on how you move your character and stuff. If you want to reset on more than just hitting the floor, you can add or change the conditions.

CardboardComputers | 2021-08-31 14:07

the code doesn’t work when on a tilemap? how should i fix this?

PopSquip | 2021-08-31 22:55

I don’t know, I don’t know what your code looks like at the moment. If your tilemap has colliders, then chances are you aren’t moving your character in a way that’s compatible with is_on_floor.

CardboardComputers | 2021-09-01 13:08

do you want me to send my code?

PopSquip | 2021-09-01 22:46