gae_platformer/scripts/player.gd

73 lines
1.8 KiB
GDScript

extends CharacterBody2D
@onready var animated_sprite_2d: AnimatedSprite2D = $AnimatedSprite2D
@onready var ray_cast_right: RayCast2D = $RayCastRight
@onready var ray_cast_left: RayCast2D = $RayCastLeft
@onready var animation_player: AnimationPlayer = $AnimationPlayer
var speed = 130.0
var jump_velocity = -300.0
var is_hurt: bool = false
func _ready() -> void:
add_to_group("player")
func take_hit() -> void:
set_physics_process(true)
set_process(true)
$CollisionShape2D.set_deferred("disabled", false)
$Sounds/DeathSound.play()
is_hurt = true
animated_sprite_2d.play("damage")
var fps = animated_sprite_2d.sprite_frames.get_animation_speed("damage")
var frame_count = animated_sprite_2d.sprite_frames.get_frame_count("damage")
await get_tree().create_timer(frame_count / fps).timeout
is_hurt = false
func die() -> void:
animated_sprite_2d.play("death")
animation_player.play("death")
func _physics_process(delta: float) -> void:
if not is_on_floor():
velocity += get_gravity() * delta
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = jump_velocity
animation_player.play("jump")
elif Input.is_action_just_pressed("jump") and is_on_wall():
if ray_cast_right.is_colliding():
velocity.y = jump_velocity
velocity.x = -300
elif ray_cast_left.is_colliding():
velocity.y = jump_velocity
velocity.x = 300
animation_player.play("jump")
var direction := Input.get_axis("move_left", "move_right")
if direction > 0:
animated_sprite_2d.flip_h = false
elif direction < 0:
animated_sprite_2d.flip_h = true
if not is_hurt:
if is_on_floor():
if direction == 0:
animated_sprite_2d.play("idle")
else:
animated_sprite_2d.play("run")
else:
animated_sprite_2d.play("jump")
if direction:
velocity.x = direction * speed
else:
velocity.x = move_toward(velocity.x, 0, speed)
move_and_slide()