70 lines
2.1 KiB
GDScript
70 lines
2.1 KiB
GDScript
class_name Player
|
|
extends CharacterBody2D
|
|
|
|
const SPEED: int = 800
|
|
|
|
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
|
|
@onready var cam: Camera2D = $Camera2D
|
|
@onready var raycast: RayCast2D = $RayCast2D
|
|
const RAYCAST_RAGE: int = 32
|
|
|
|
|
|
@export var tilemap: TileMapLayer
|
|
var tilesize: int = 32
|
|
var position_limit_rect: Rect2
|
|
|
|
func _ready() -> void:
|
|
EventManager.player = self
|
|
var used_tilemap_rect: Rect2i = tilemap.get_used_rect()
|
|
tilesize = tilemap.tile_set.tile_size.x
|
|
|
|
cam.limit_left = used_tilemap_rect.position.x * tilesize
|
|
cam.limit_top = used_tilemap_rect.position.y * tilesize
|
|
cam.limit_right = used_tilemap_rect.end.x * tilesize
|
|
cam.limit_bottom = used_tilemap_rect.end.y * tilesize
|
|
|
|
var margin: float = float(tilesize) / 4
|
|
|
|
position_limit_rect = Rect2(
|
|
Vector2(cam.limit_left + margin, cam.limit_top - margin),
|
|
Vector2(
|
|
(cam.limit_right - margin) - (cam.limit_left + margin),
|
|
(cam.limit_bottom - margin / 2) - (cam.limit_top + margin / 2)
|
|
)
|
|
)
|
|
|
|
func _process(_delta: float) -> void:
|
|
if Input.is_action_just_pressed("interact") && raycast.is_colliding() && raycast.get_collider() is Interactable:
|
|
var interactable: Interactable = raycast.get_collider()
|
|
interactable.interact()
|
|
|
|
func _physics_process(delta: float) -> void:
|
|
if EventManager.player_free:
|
|
var input := Input.get_vector("move_left", "move_right", "move_up", "move_down").normalized()
|
|
|
|
var raycast_input := Vector2.ZERO
|
|
if abs(input.x) > abs(input.y):
|
|
raycast_input.x = sign(input.x)
|
|
elif abs(input.y) > 0:
|
|
raycast_input.y = sign(input.y)
|
|
if raycast_input != Vector2.ZERO:
|
|
raycast.target_position = raycast_input * RAYCAST_RAGE
|
|
|
|
velocity = input * delta * SPEED * 3
|
|
|
|
move_and_slide()
|
|
position = position.clamp(position_limit_rect.position, position_limit_rect.end)
|
|
|
|
if velocity.length() != 0:
|
|
animated_sprite.play()
|
|
animated_sprite.flip_h = false
|
|
if abs(velocity.x) > abs(velocity.y):
|
|
animated_sprite.animation = "side"
|
|
animated_sprite.flip_h = velocity.x < 0
|
|
elif velocity.y < 0:
|
|
animated_sprite.animation = "up"
|
|
else:
|
|
animated_sprite.animation = "down"
|
|
else:
|
|
animated_sprite.stop()
|