Skip to content

Instantly share code, notes, and snippets.

@cbscribe
Last active July 1, 2021 17:08
Show Gist options
  • Save cbscribe/c4b9d5f5f00289e567f04812c7ec1b13 to your computer and use it in GitHub Desktop.
Save cbscribe/c4b9d5f5f00289e567f04812c7ec1b13 to your computer and use it in GitHub Desktop.
Player code for Godot platformer
extends KinematicBody2D
enum {IDLE, RUN, JUMP, HURT, DEAD}
var state
var anim
var new_anim
var run_speed = 150
var jump_speed = -320
var gravity = 750
var velocity = Vector2.ZERO
var life = 3
func _ready():
change_state(IDLE)
func change_state(new_state):
state = new_state
match state:
IDLE:
new_anim = "idle"
RUN:
new_anim = "run"
HURT:
new_anim = "hurt"
velocity.y = -200
velocity.x = 100 * (int($Sprite.flip_h) * 2 - 1)#sign(velocity.x)
life -= 1
yield(get_tree().create_timer(0.5), "timeout")
change_state(IDLE)
if life <= 0:
change_state(DEAD)
JUMP:
new_anim = "jump_up"
DEAD:
get_tree().reload_current_scene()
func _physics_process(delta):
if new_anim != anim:
anim = new_anim
$AnimationPlayer.play(anim)
get_input()
velocity.y += gravity * delta
velocity = move_and_slide(velocity, Vector2.UP)
for i in get_slide_count():
var collision = get_slide_collision(i)
if collision.collider.name == "Spikes":
hurt()
if collision.collider.is_in_group("enemies"):
var feet = (position + $CollisionShape2D.shape.extents).y
if feet < collision.collider.position.y:
collision.collider.hurt()
velocity.y = -200
if state == JUMP and is_on_floor():
change_state(IDLE)
if state == JUMP and velocity.y > 0:
new_anim = "jump_down"
if position.y > 2000:
change_state(DEAD)
func get_input():
if state == HURT:
return
var right = Input.is_action_pressed("right")
var left = Input.is_action_pressed("left")
var jump = Input.is_action_just_pressed("jump")
velocity.x = 0
if right:
velocity.x += run_speed
$Sprite.flip_h = false
if left:
velocity.x -= run_speed
$Sprite.flip_h = true
if jump and is_on_floor():
change_state(JUMP)
velocity.y = jump_speed
if state == IDLE and velocity.x != 0:
change_state(RUN)
if state == RUN and velocity.x == 0:
change_state(IDLE)
if state in [IDLE, RUN] and not is_on_floor():
change_state(JUMP)
func hurt():
if state != HURT:
change_state(HURT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment