player.gd 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. extends CharacterBody2D
  2. const MOTION_SPEED = 90.0
  3. const BOMB_RATE = 0.5
  4. @export
  5. var synced_position := Vector2()
  6. @export
  7. var stunned = false
  8. @onready
  9. var inputs = $Inputs
  10. var last_bomb_time = BOMB_RATE
  11. var current_anim = ""
  12. func _ready():
  13. stunned = false
  14. position = synced_position
  15. if str(name).is_valid_int():
  16. get_node("Inputs/InputsSync").set_multiplayer_authority(str(name).to_int())
  17. func _physics_process(delta):
  18. if multiplayer.multiplayer_peer == null or str(multiplayer.get_unique_id()) == str(name):
  19. # The client which this player represent will update the controls state, and notify it to everyone.
  20. inputs.update()
  21. if multiplayer.multiplayer_peer == null or is_multiplayer_authority():
  22. # The server updates the position that will be notified to the clients.
  23. synced_position = position
  24. # And increase the bomb cooldown spawning one if the client wants to.
  25. last_bomb_time += delta
  26. if not stunned and is_multiplayer_authority() and inputs.bombing and last_bomb_time >= BOMB_RATE:
  27. last_bomb_time = 0.0
  28. get_node("../../BombSpawner").spawn([position, str(name).to_int()])
  29. else:
  30. # The client simply updates the position to the last known one.
  31. position = synced_position
  32. if not stunned:
  33. # Everybody runs physics. I.e. clients tries to predict where they will be during the next frame.
  34. velocity = inputs.motion * MOTION_SPEED
  35. move_and_slide()
  36. # Also update the animation based on the last known player input state
  37. var new_anim = "standing"
  38. if inputs.motion.y < 0:
  39. new_anim = "walk_up"
  40. elif inputs.motion.y > 0:
  41. new_anim = "walk_down"
  42. elif inputs.motion.x < 0:
  43. new_anim = "walk_left"
  44. elif inputs.motion.x > 0:
  45. new_anim = "walk_right"
  46. if stunned:
  47. new_anim = "stunned"
  48. if new_anim != current_anim:
  49. current_anim = new_anim
  50. get_node("anim").play(current_anim)
  51. func set_player_name(value):
  52. get_node("label").text = value
  53. @rpc("call_local")
  54. func exploded(_by_who):
  55. if stunned:
  56. return
  57. stunned = true
  58. get_node("anim").play("stunned")