extends Area2D

export var vitesse = 400  # vitesse en pixel/sec
var screen_size  # taille de la fenetre
signal perdu

func _ready():
	screen_size = get_viewport_rect().size
	hide()
	
func _process(delta):
	var velocity = Vector2(0, 0)
	var animated = false
	
	# animation diagonales
	
	if Input.is_action_pressed('ui_up') and (Input.is_action_pressed('ui_left') or Input.is_action_pressed('ui_right')):
		$AnimatedSprite.play("haut")
		animated = true
	if Input.is_action_pressed('ui_down') and (Input.is_action_pressed('ui_left') or Input.is_action_pressed('ui_right')):
		$AnimatedSprite.play("bas")
		animated = true
	
	# déplacement et animation gauche droite haut bas
	
	if Input.is_action_pressed("ui_right"):
		velocity.x += 1
		if not animated:
			$AnimatedSprite.play("droite")
	if Input.is_action_pressed("ui_left"):
		velocity.x -= 1
		if not animated:
			$AnimatedSprite.play("gauche")
	if Input.is_action_pressed("ui_down"):
		velocity.y += 1
		if not animated:
			$AnimatedSprite.play("bas")
	if Input.is_action_pressed("ui_up"):
		velocity.y -= 1
		if not animated:
			$AnimatedSprite.play("haut")
	
	# vitesse indentique en diagonale
	if velocity.length() > 0:
		velocity = velocity.normalized() * vitesse
	else:
		$AnimatedSprite.set_frame(0)
		$AnimatedSprite.stop()
		
	position += velocity * delta
	position.x = clamp(position.x, 0, screen_size.x)
	position.y = clamp(position.y, 0, screen_size.y)

func _on_Joueur_body_entered(_body): # _body au lieu de body parce que on ne l'utilise pas
	hide()
	emit_signal("perdu")
	$CollisionShape2D.set_deferred("disabled", true)

func start(pos):
	position = pos
	show()
	$CollisionShape2D.disabled = false
