Player.gd 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. class_name Player
  2. extends Area2D
  3. signal hit
  4. enum State {SLEEPING, DODGING, DEAD}
  5. export var speed = 400 # pixel / sec
  6. var screen
  7. var target = Vector2()
  8. var target_reached = true
  9. var _current_state
  10. func spawn(pos):
  11. _current_state = State.DODGING
  12. $CollisionShape2D.disabled = false
  13. go_to(pos)
  14. func sleep():
  15. _current_state = State.SLEEPING
  16. $AnimatedSprite.animation = "sleep"
  17. $AnimatedSprite.play()
  18. func die():
  19. _current_state = State.DEAD
  20. $AnimatedSprite.animation = "die"
  21. $AnimatedSprite.play()
  22. func _ready():
  23. screen = get_viewport_rect()
  24. sleep()
  25. func _process(delta: float):
  26. if _current_state == State.DODGING:
  27. dodge(delta)
  28. func dodge(delta: float):
  29. var velocity = get_velocity_from_action()
  30. if velocity == Vector2.ZERO :
  31. velocity = get_velocity_from_target(delta)
  32. if velocity.length_squared() > 0:
  33. velocity = velocity.normalized() * speed
  34. position += velocity * delta
  35. position.x = clamp(position.x, 0, screen.size.x)
  36. position.y = clamp(position.y, 0, screen.size.y)
  37. $AnimatedSprite.animation = "move"
  38. $AnimatedSprite.flip_h = velocity.x < 0
  39. else:
  40. $AnimatedSprite.animation = "idle"
  41. func go_to(pos: Vector2):
  42. target = pos
  43. target_reached = false
  44. func _input(event):
  45. if event is InputEventMouseButton or event is InputEventMouseMotion :
  46. go_to(event.position)
  47. func _on_Player_body_entered(_body):
  48. die()
  49. emit_signal("hit")
  50. $CollisionShape2D.set_deferred("disabled", true)
  51. func get_velocity_from_action() -> Vector2:
  52. var velocity = Vector2()
  53. if Input.is_action_pressed("ui_right"):
  54. velocity.x += 1
  55. if Input.is_action_pressed("ui_left"):
  56. velocity.x -= 1
  57. if Input.is_action_pressed("ui_down"):
  58. velocity.y += 1
  59. if Input.is_action_pressed("ui_up"):
  60. velocity.y -= 1
  61. return velocity;
  62. func get_velocity_from_target(delta):
  63. if target_reached :
  64. return Vector2.ZERO
  65. var path = target - position
  66. if path.length_squared() < speed * speed * delta * delta :
  67. target_reached = true
  68. return Vector2.ZERO
  69. return path