Skip to content

Instantly share code, notes, and snippets.

@pixelchai
Created June 25, 2020 21:20
Show Gist options
  • Save pixelchai/121829ee02c16945fe8574655100fb79 to your computer and use it in GitHub Desktop.
Save pixelchai/121829ee02c16945fe8574655100fb79 to your computer and use it in GitHub Desktop.
Godot player movement script -- with double jumping
extends KinematicBody2D
const UP = Vector2(0, -1)
const GRAVITY = 20
const ACCELERATION = 200
const MAX_SPEED = 600
const JUMP_HEIGHT = -750
var motion = Vector2()
var num_jumps = 0
var jump_timer = 10000 # +inf
func _physics_process(delta):
var d = delta * 70
motion.y += GRAVITY * d # apply gravity
var moving = false
if Input.is_action_pressed("ui_right"):
motion.x = min(motion.x + ACCELERATION * d, MAX_SPEED) # accelerate right up to MAX_SPEED
$Sprite.flip_h = false
moving = true
elif Input.is_action_pressed("ui_left"):
motion.x = max(motion.x - ACCELERATION * d, -MAX_SPEED) # as above but left
$Sprite.flip_h = true
moving = true
if is_on_floor():
if moving:
$Sprite.play("run")
else:
$Sprite.play("idle")
if Input.is_action_pressed("ui_up") and num_jumps < 2 and jump_timer > 0.3:
motion.y = JUMP_HEIGHT
num_jumps += 1
jump_timer = 0
if num_jumps > 1:
$Sprite.frame = 0 # reset animation
$Sprite.play("doublejump")
else:
$Sprite.play("jump") # play animation
motion = move_and_slide(motion, UP)
jump_timer += delta
if is_on_floor():
num_jumps = 0 # below applying motion so that num_jumps not incremented then immediately reset
motion.x = lerp(motion.x, 0, 0.2 * d) # floor friction
else: # not on floor (= in air)
# if motion.y < 0: # going up
# if $Sprite.animation != "jump":
# $Sprite.play("jump")
if motion.y >= 0: # going down
if $Sprite.animation != "fall":
$Sprite.play("fall")
motion.x = lerp(motion.x, 0, 0.02 * d) # less friction in air
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment