Player.gd 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. extends Area2D
  2. class_name Player
  3. @export var speed := 400.
  4. var _screen_size: Vector2
  5. var _sprite: AnimatedSprite2D
  6. var _shape: CollisionShape2D
  7. func start(starting_position: Vector2) -> void :
  8. position = starting_position
  9. show()
  10. _shape.disabled = false
  11. pass
  12. func _ready() -> void:
  13. hide()
  14. _screen_size = get_viewport_rect().size
  15. _sprite = $Sprite as AnimatedSprite2D
  16. _shape = $Shape as CollisionShape2D
  17. pass # Replace with function body.
  18. func _process(delta: float) -> void:
  19. var velocity := Vector2.ZERO
  20. if Input.is_action_pressed("move_right") :
  21. velocity.x += 1
  22. if Input.is_action_pressed("move_left") :
  23. velocity.x -= 1
  24. if Input.is_action_pressed("move_down"):
  25. velocity.y += 1
  26. if Input.is_action_pressed("move_up") :
  27. velocity.y -= 1
  28. if velocity.length() > 0 :
  29. velocity = velocity.normalized() * speed
  30. _sprite.play()
  31. else:
  32. _sprite.stop()
  33. position += velocity * delta
  34. # Make it impossible to leave the screen.
  35. position = position.clamp(Vector2.ZERO, _screen_size)
  36. if velocity.x != 0 :
  37. _sprite.animation = "walk"
  38. _sprite.flip_v = false
  39. _sprite.flip_h = velocity.x < 0
  40. elif velocity.y != 0 :
  41. _sprite.animation = "up"
  42. _sprite.flip_v = velocity.y > 0
  43. pass
  44. signal hit
  45. func _on_body_entered(body: Node2D) -> void:
  46. hide()
  47. hit.emit()
  48. _shape.set_deferred("disabled", true)
  49. pass