Player.gd 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. extends Area2D
  2. signal hit
  3. export var speed = 400 # pixel / sec
  4. var screen
  5. var target = Vector2()
  6. var target_reached = true
  7. func spawn(atPos):
  8. position = atPos
  9. show()
  10. $CollisionShape2D.disabled = false
  11. func die():
  12. hide()
  13. func _ready():
  14. hide()
  15. screen = get_viewport_rect()
  16. func _process(delta):
  17. var velocity = get_velocity_from_action()
  18. if velocity == Vector2.ZERO :
  19. velocity = get_velocity_from_target(delta)
  20. if velocity.length() > 0:
  21. velocity = velocity.normalized() * speed
  22. $AnimatedSprite.play()
  23. else:
  24. $AnimatedSprite.stop()
  25. position += velocity * delta
  26. position.x = clamp(position.x, 0, screen.size.x)
  27. position.y = clamp(position.y, 0, screen.size.y)
  28. if velocity.x != 0:
  29. $AnimatedSprite.animation = "right"
  30. $AnimatedSprite.flip_v = false
  31. $AnimatedSprite.flip_h = velocity.x < 0
  32. elif velocity.y != 0:
  33. $AnimatedSprite.animation = "up"
  34. $AnimatedSprite.flip_v = velocity.y > 0
  35. func _input(event):
  36. if event is InputEventMouseButton or event is InputEventMouseMotion :
  37. target = event.position
  38. target_reached = false
  39. func _on_Player_body_entered(_body):
  40. die()
  41. emit_signal("hit")
  42. $CollisionShape2D.set_deferred("disabled", true)
  43. func get_velocity_from_action() -> Vector2:
  44. var velocity = Vector2()
  45. if Input.is_action_pressed("ui_right"):
  46. velocity.x += 1
  47. if Input.is_action_pressed("ui_left"):
  48. velocity.x -= 1
  49. if Input.is_action_pressed("ui_down"):
  50. velocity.y += 1
  51. if Input.is_action_pressed("ui_up"):
  52. velocity.y -= 1
  53. return velocity;
  54. func get_velocity_from_target(delta):
  55. if target_reached :
  56. return Vector2.ZERO
  57. var path = target - position
  58. if path.length_squared() < speed * speed * delta * delta :
  59. target_reached = true
  60. return Vector2.ZERO
  61. return path