Skip to content

Instantly share code, notes, and snippets.

@SphericalKat
Created May 12, 2024 15:27
Show Gist options
  • Save SphericalKat/03ac9dcf02249328490f41fa0c5368a4 to your computer and use it in GitHub Desktop.
Save SphericalKat/03ac9dcf02249328490f41fa0c5368a4 to your computer and use it in GitHub Desktop.
extends CharacterBody2D
@onready var coyote_timer = $Timer
const SPEED = 130.0
const JUMP_VELOCITY = -300.0
var can_jump = true
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
func jump():
velocity.y = JUMP_VELOCITY
can_jump = false
func _physics_process(delta):
# this needs to happen first, otherwise can_jump can get set to true
# if the player presses jump twice a frame, which leads to double jumping
# because is_on_floor is true, and can_jump was set to false during first jump
if can_jump == false and is_on_floor():
can_jump = true
#timer.start()
# add gravity
if not is_on_floor():
velocity.y += gravity * delta
# handle jump
if Input.is_action_just_pressed("ui_accept") and can_jump:
jump()
# start the coyote timer if the player just moved off a ledge (without jumping)
# can_jump - set to true because that's the default
# is_on_floor - will return false because the player is off the ground
# if timer is stopped, start it, giving the player 0.3s
# of grace period when they can still jump
if can_jump and !is_on_floor() and coyote_timer.is_stopped():
coyote_timer.start()
# get the input direction and handle the movement/deceleration
# todo: replace UI actions with custom gameplay actions
var direction = Input.get_axis("ui_left", "ui_right")
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
move_and_slide()
func _on_timer_timeout():
can_jump = false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment