godot-platformer-template/Player.gd
2020-11-23 01:06:21 +08:00

86 lines
2.1 KiB
GDScript

extends KinematicBody2D
# list of things we should to implement:
# https://twitter.com/MaddyThorson/status/1238338584479813637
# Done:
# 1. Coyote time.
# 2. Jump buffering.
# 3. Halved gravity jump peak.
# TODO:
# 4. Jump corner correction.
# 8. You can actually wall jump 2 pixels from a wall.
const COYOTE_TIME = 0.1
const BUFFER_JUMP_TIME = 0.1
const VAR_JUMP_TIME = 0.2 # hold jump to jump higher
const JUMP_SPEED = -160
const MAX_FALL = 160
const GRAVITY = 1000
const HALF_GRAV_THRESHOLD = 40
const MAX_RUN = 100
const RUN_ACCEL = 800
const RUN_ACCEL_AIR_MULT = 0.8
var speed = Vector2.ZERO
var buffer_jump_grace = 0
var coyote_jump_grace = 0
var var_jump = 0
onready var sprite = $Sprite
func _physics_process(delta):
if buffer_jump_grace > 0:
buffer_jump_grace -= delta
if coyote_jump_grace > 0:
coyote_jump_grace -= delta
if var_jump > 0:
var_jump -= delta
var on_ground = is_on_floor()
if on_ground:
coyote_jump_grace = COYOTE_TIME
else:
if Input.is_action_just_pressed("player_jump"):
buffer_jump_grace = BUFFER_JUMP_TIME
# Vertical Control
if (coyote_jump_grace > 0 && (Input.is_action_just_pressed("player_jump") || buffer_jump_grace > 0)):
# Jumping
buffer_jump_grace = 0
coyote_jump_grace = 0
var_jump = VAR_JUMP_TIME
speed.y = JUMP_SPEED
else:
# Gravity
var mult = 1
if Input.is_action_pressed("player_jump") && abs(speed.y) <= HALF_GRAV_THRESHOLD:
mult = 0.5
# speed.y += min(MAX_FALL, GRAVITY * mult * delta)
speed.y = move_toward(speed.y, MAX_FALL, GRAVITY * mult * delta)
# Variable Jumping
if Input.is_action_just_released("player_jump"):
var_jump = 0
if var_jump > 0 && Input.is_action_pressed("player_jump"):
speed.y = JUMP_SPEED
# Horizontal Control
var x_input = Input.get_action_strength("player_right") - Input.get_action_strength("player_left")
if x_input != 0:
sprite.flip_h = x_input < 0
var accel = RUN_ACCEL
if !on_ground:
accel *= RUN_ACCEL_AIR_MULT
speed.x = move_toward(speed.x, x_input * MAX_RUN, accel * delta)
# Apply movement
speed = move_and_slide(speed, Vector2.UP)