TheFlipSide/Scripts/player.gd

88 lines
2.5 KiB
GDScript

extends CharacterBody2D
@onready var tile_layer : TileMapLayer = $"../TileMapLayer"
@onready var level : Node2D = $".."
@onready var particles : GPUParticles2D = $GPUParticles2D
@onready var fade : ColorRect = $Fade/Rectangle
@export_category("Movement")
@export var acceleration : float = 50
@export var braking : float = 20
@export var move_speed : float = 100
var move_input : float
var dead : bool
func _ready() -> void:
respawn()
func _physics_process(delta: float) -> void:
if dead == false:
#Horizontal movement.
move_input = Input.get_axis("move_left", "move_right")
if move_input != 0:
velocity.x = lerp(velocity.x, move_input * move_speed, acceleration * delta)
else:
velocity.x = lerp(velocity.x, 0.0, braking * delta)
#Vertical movement.
velocity.y += al_globals.gravity * delta
if Input.is_action_just_pressed("flip") and (is_on_floor() or is_on_ceiling()):
al_globals.gravity *= -1
if velocity.y > 500 and not (is_on_floor() or is_on_ceiling()):
particles.emitting = true
else:
particles.emitting = false
move_and_slide() #Allow physics control.
tilemap_detection() #Checks for tiles with the "Spike" custom data enabled.
func tilemap_detection() -> void:
#Adapted from Godot forum post.
#Get current tile, and then put the data from it into a variable.
var tile_coord = tile_layer.local_to_map(tile_layer.to_local(global_position))
var tile_data = tile_layer.get_cell_tile_data(tile_coord)
#If it has data, check for it. If it has the "spike" custom data, ensure the gravity is set back to normal, and then reset the level.
if tile_data:
#Checks for spikes.
var spike_data = tile_data.get_custom_data("spike")
if spike_data == true:
death(false)
#Checks for exits.
var exit_data = tile_data.get_custom_data("exit")
if exit_data == true:
next_level(level.next_level) #Pulls next level data from parent Node2D.
func death(fallen: bool) -> void:
dead = true
if !fallen:
velocity.x = 0
velocity.y = 0
scale.x = lerp(scale.x, 0.0, 0.1)
scale.y = lerp(scale.y, 0.0, 0.1)
if al_globals.gravity < 0:
al_globals.gravity *= -1
await get_tree().create_timer(1.0).timeout
respawn()
func respawn() -> void:
dead = false
scale.x = lerp(scale.x, 1.0, 0.1)
scale.y = lerp(scale.y, 1.0, 0.1)
position.x = level.startPosX
position.y = level.startPosY
func next_level(level : String):
dead == true
get_tree().change_scene_to_file(level)
func _on_visible_on_screen_notifier_2d_screen_exited() -> void:
if !dead:
death(true)