1
0
Fork 0
1bit-godot-course/metroidvania/Scenes/Player.gd

71 lines
1.9 KiB
GDScript3
Raw Normal View History

2021-01-26 22:04:34 +00:00
extends KinematicBody2D
export (int) var acceleration = 512
export (int) var max_speed = 64
export (float) var friction = 0.25
export (int) var gravity = 200
export (int) var jump_force = 128
export (int) var max_slope = 46
var motion = Vector2.ZERO
var snap_vector = Vector2.ZERO
onready var sprite = $Sprite
onready var animation = $Animation
func _physics_process(delta):
var input_vector = get_input_vector()
apply_horizontal_force(input_vector, delta)
apply_friction(input_vector)
update_snap_vector()
jump_check()
apply_gravity(delta)
update_animations(input_vector)
move()
func get_input_vector():
var input_vector = Vector2.ZERO
input_vector.x = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")
return input_vector
func apply_horizontal_force(input_vector, delta):
if input_vector.x != 0:
motion.x += input_vector.x * acceleration * delta
motion.x = clamp(motion.x, -max_speed, max_speed) # Set the max motion
func apply_friction(input_vector):
if input_vector.x == 0 and is_on_floor():
motion.x = lerp(motion.x, 0, friction)
func update_snap_vector():
if is_on_floor():
snap_vector = Vector2.DOWN
func jump_check():
if is_on_floor():
if Input.is_action_just_pressed("ui_select"):
motion.y = -jump_force
snap_vector = Vector2.ZERO
else:
if Input.is_action_just_released("ui_select"):# and motion.y < -jump_force/2:
motion.y = motion.y/2
func apply_gravity(delta):
motion.y += gravity * delta
motion.y = min(motion.y, jump_force)
func update_animations(input_vector):
if input_vector.x != 0:
# Reverses the sprite if the direction is -x ?
sprite.scale.x = sign(input_vector.x)
animation.play("Run")
else:
animation.play("Idle")
if not is_on_floor():
animation.play("Jump")
func move():
motion = move_and_slide_with_snap(motion, snap_vector * 4, Vector2.UP, true, 4, deg2rad(max_slope), false)