Need to know if my character is touching the ground

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

I need to know if my character is touching the ground so it is only capable of jumping when it is touching the ground

Here is how i tried to make it:

extends KinematicBody2D

export (int) var speed = 200
export var jump_height = 7000
var gravity = 1100
var velocity = Vector2()
var on_ground = false
var fallspeed = 350

func get_input(delta):
	velocity = Vector2()
	if Input.is_action_pressed("Move_Right"):
		velocity.x += speed 
	if Input.is_action_pressed("Move_Left"):
		velocity.x -= speed
	if Input.is_action_pressed("Move_Down"):
		velocity.y += speed
	if Input.is_action_pressed("Move_Up"):
		velocity.y -= speed
	if Input.is_action_pressed("Dash"):
		speed = 250
	else :
		speed = 200
	if Input.is_action_just_pressed("Jump"):
		position.y -= jump_height * delta
		on_ground = false
	if  on_ground == false:
		velocity.y += fallspeed * delta
	velocity = velocity.normalized() * speed
func _physics_process(delta):
	velocity = move_and_slide(velocity)

(edited original post to format code for the forum)

jgodfrey | 2023-01-03 23:55

:bust_in_silhouette: Reply From: jgodfrey

A KinematicBody2D already provides an is_on_floor() method to do this automagically. As long as things are set up properly and you’re calling move_and_slide() in each frame (which you are), you should be able to use that to determine if your character is grounded.

ohh okay, i understand, Thank you!

Joxer | 2023-01-03 23:50