Player.gd 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. extends Area2D
  2. signal hit
  3. @export var speed = 400 # How fast the player will move (pixels/sec).
  4. var screen_size # Size of the game window.
  5. func _ready():
  6. screen_size = get_viewport_rect().size
  7. hide()
  8. func _process(delta):
  9. var velocity = Vector2.ZERO # The player's movement vector.
  10. if Input.is_action_pressed(&"move_right"):
  11. velocity.x += 1
  12. if Input.is_action_pressed(&"move_left"):
  13. velocity.x -= 1
  14. if Input.is_action_pressed(&"move_down"):
  15. velocity.y += 1
  16. if Input.is_action_pressed(&"move_up"):
  17. velocity.y -= 1
  18. if velocity.length() > 0:
  19. velocity = velocity.normalized() * speed
  20. $AnimatedSprite2D.play()
  21. else:
  22. $AnimatedSprite2D.stop()
  23. position += velocity * delta
  24. position = position.clamp(Vector2.ZERO, screen_size)
  25. if velocity.x != 0:
  26. $AnimatedSprite2D.animation = &"right"
  27. $AnimatedSprite2D.flip_v = false
  28. $Trail.rotation = 0
  29. $AnimatedSprite2D.flip_h = velocity.x < 0
  30. elif velocity.y != 0:
  31. $AnimatedSprite2D.animation = &"up"
  32. rotation = PI if velocity.y > 0 else 0
  33. func start(pos):
  34. position = pos
  35. rotation = 0
  36. show()
  37. $CollisionShape2D.disabled = false
  38. func _on_Player_body_entered(_body):
  39. hide() # Player disappears after being hit.
  40. hit.emit()
  41. # Must be deferred as we can't change physics properties on a physics callback.
  42. $CollisionShape2D.set_deferred(&"disabled", true)