Player.gd 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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.x = clamp(position.x, 0, screen_size.x)
  25. position.y = clamp(position.y, 0, screen_size.y)
  26. if velocity.x != 0:
  27. $AnimatedSprite2D.animation = "right"
  28. $AnimatedSprite2D.flip_v = false
  29. $AnimatedSprite2D.flip_h = velocity.x < 0
  30. elif velocity.y != 0:
  31. $AnimatedSprite2D.animation = "up"
  32. $AnimatedSprite2D.flip_v = velocity.y > 0
  33. func start(pos):
  34. position = pos
  35. show()
  36. $CollisionShape2D.disabled = false
  37. func _on_Player_body_entered(_body):
  38. hide() # Player disappears after being hit.
  39. emit_signal("hit")
  40. # Must be deferred as we can't change physics properties on a physics callback.
  41. $CollisionShape2D.set_deferred("disabled", true)