player.gd 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. extends CharacterBody3D
  2. const SPEED = 5.0
  3. const JUMP_VELOCITY = 4.5
  4. # Get the gravity from the project settings to be synced with RigidBody nodes.
  5. var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")
  6. # Set by the authority, synchronized on spawn.
  7. @export var player := 1 :
  8. set(id):
  9. player = id
  10. # Give authority over the player input to the appropriate peer.
  11. $PlayerInput.set_multiplayer_authority(id)
  12. # Player synchronized input.
  13. @onready var input = $PlayerInput
  14. func _ready():
  15. # Set the camera as current if we are this player.
  16. if player == multiplayer.get_unique_id():
  17. $Camera3D.current = true
  18. # Only process on server.
  19. # EDIT: Left the client simulate player movement too to compesate network latency.
  20. # set_physics_process(multiplayer.is_server())
  21. func _physics_process(delta):
  22. # Add the gravity.
  23. if not is_on_floor():
  24. velocity.y -= gravity * delta
  25. # Handle Jump.
  26. if input.jumping and is_on_floor():
  27. velocity.y = JUMP_VELOCITY
  28. # Reset jump state.
  29. input.jumping = false
  30. # Handle movement.
  31. var direction = (transform.basis * Vector3(input.direction.x, 0, input.direction.y)).normalized()
  32. if direction:
  33. velocity.x = direction.x * SPEED
  34. velocity.z = direction.z * SPEED
  35. else:
  36. velocity.x = move_toward(velocity.x, 0, SPEED)
  37. velocity.z = move_toward(velocity.z, 0, SPEED)
  38. move_and_slide()