89 lines
2.3 KiB
GDScript3
89 lines
2.3 KiB
GDScript3
|
extends KinematicBody2D
|
||
|
class_name Player
|
||
|
|
||
|
export var speed: Vector2 = Vector2(150.0, 195.0)
|
||
|
export var gravity: = 410.0
|
||
|
export var max_gravity:= 450.0
|
||
|
export var respawn_position:=Vector2.ZERO
|
||
|
|
||
|
|
||
|
signal landed
|
||
|
signal jumping
|
||
|
signal died
|
||
|
|
||
|
var _velocity: Vector2 = Vector2.ZERO
|
||
|
var _landing_position:Vector2 = Vector2.ZERO
|
||
|
var _in_air = false;
|
||
|
var _alive := false;
|
||
|
func _ready() -> void:
|
||
|
$AnimationPlayer.play("fade_in")
|
||
|
respawn_position = position
|
||
|
|
||
|
func _physics_process(delta: float) -> void:
|
||
|
if _alive:
|
||
|
var is_jump_canceled: = Input.is_action_just_released("jump") and _velocity.y < 0.0
|
||
|
var direction: = get_direction()
|
||
|
_velocity = calculate_move_velocity(_velocity, direction, speed, is_jump_canceled, delta)
|
||
|
_velocity = move_and_slide(_velocity, Vector2.UP)
|
||
|
update_sprite(direction)
|
||
|
if is_on_floor() and _in_air:
|
||
|
_in_air = false
|
||
|
emit_signal("landed", position)
|
||
|
|
||
|
#func get_class(): return "Player"
|
||
|
|
||
|
func get_direction() -> Vector2:
|
||
|
return Vector2(
|
||
|
Input.get_action_strength("direction_right") - Input.get_action_strength("direction_left"),
|
||
|
-1.0 if Input.is_action_just_pressed("jump") and is_on_floor() else 1.0
|
||
|
)
|
||
|
|
||
|
func calculate_move_velocity(linear_velosity:Vector2, direction:Vector2, speed:Vector2, is_jump_canceled:bool, delta:float)->Vector2:
|
||
|
var output: = linear_velosity
|
||
|
output.x = speed.x * direction.x
|
||
|
output.y += gravity * delta
|
||
|
if direction.y == -1.0:
|
||
|
_in_air = true
|
||
|
output.y = speed.y * direction.y
|
||
|
emit_signal("jumping", position)
|
||
|
|
||
|
|
||
|
if is_jump_canceled:
|
||
|
output.y = 0
|
||
|
if output.y < max_gravity*-1:
|
||
|
output.y = max_gravity
|
||
|
if output.y > 0 and !is_on_floor():
|
||
|
_in_air = true;
|
||
|
return output;
|
||
|
|
||
|
func _respawn():
|
||
|
position = respawn_position
|
||
|
_velocity = Vector2.ZERO
|
||
|
$AnimationPlayer.play("fade_in")
|
||
|
|
||
|
func _revive():
|
||
|
_alive = true
|
||
|
|
||
|
func update_sprite(direction:Vector2)->void:
|
||
|
var air_animation = "jump" if _velocity.y <= 0 else "fall"
|
||
|
if direction.x > 0:
|
||
|
$AnimationPlayer.play("run" if is_on_floor() else air_animation)
|
||
|
$Sprite.flip_h = false
|
||
|
elif direction.x < 0:
|
||
|
$AnimationPlayer.play("run" if is_on_floor() else air_animation)
|
||
|
$Sprite.flip_h = true
|
||
|
else:
|
||
|
$AnimationPlayer.play("idle")
|
||
|
if !is_on_floor():
|
||
|
$AnimationPlayer.play(air_animation)
|
||
|
|
||
|
func _on_die_animation_done():
|
||
|
emit_signal("died")
|
||
|
_respawn()
|
||
|
|
||
|
func die():
|
||
|
_alive = false
|
||
|
$AnimationPlayer.play("die")
|
||
|
|
||
|
|