extends Area2D signal hit @export var max_speed: float = 200 @export var acceleration: float = 75 @export var friction: float = 0.2 var player_velocity: Vector2 = Vector2.ZERO var screen_size: Vector2 var screen_area: Rect2 func _ready() -> void: screen_size = get_viewport_rect().size var player_size: Vector2 = $CollisionShape2D.shape.get_rect().size screen_area = Rect2(Vector2.ZERO, screen_size) screen_area.position.x += player_size.x / 2 screen_area.position.y += player_size.y / 2 screen_area.size.x -= player_size.x / 2 screen_area.size.y -= player_size.y / 2 func _process(delta: float) -> void: var apply_velocity: Vector2 = Vector2.ZERO if Input.is_action_pressed("move_right"): apply_velocity += Vector2.RIGHT if Input.is_action_pressed("move_left"): apply_velocity += Vector2.LEFT if Input.is_action_pressed("move_up"): apply_velocity += Vector2.UP if Input.is_action_pressed("move_down"): apply_velocity += Vector2.DOWN apply_velocity = apply_velocity.normalized() player_velocity -= player_velocity * friction player_velocity += apply_velocity * acceleration * delta if player_velocity.length() > max_speed: player_velocity = player_velocity.normalized() * max_speed if player_velocity.length() < 0.1: player_velocity = Vector2.ZERO position += player_velocity position = position.clamp(screen_area.position, screen_area.size) if player_velocity.y > 0: $AnimatedSprite2D.flip_v = true elif player_velocity.y < 0: $AnimatedSprite2D.flip_v = false if player_velocity.length() > 0: $AnimatedSprite2D.play() else: $AnimatedSprite2D.stop() func start(pos): position = pos show() $CollisionShape2D.disabled = false func disable(): hide() # Must be deferred as we can't change physics properties on a physics callback. $CollisionShape2D.set_deferred("disabled", true) func _on_body_entered(body): if body.is_in_group("mobs"): hit.emit() body.hit_player()