Advertisement
Guest User

Godot 4 Simple FPS Controller

a guest
Mar 3rd, 2023
4,599
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. extends CharacterBody3D
  2.  
  3. const SPEED = 5.0
  4. const JUMP_VELOCITY = 4.5
  5.  
  6. # Get the gravity from the project settings to be synced with RigidBody nodes.
  7. var gravity: float = ProjectSettings.get_setting("physics/3d/default_gravity")
  8.  
  9. @onready var camera: Camera3D = $Camera3D
  10.  
  11. func _ready() -> void:
  12. Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
  13.  
  14.  
  15. func _unhandled_input(event: InputEvent) -> void:
  16. if event is InputEventMouseMotion:
  17. rotate_y(-event.relative.x * .005)
  18. camera.rotate_x(-event.relative.y * .005)
  19. camera.rotation.x = clamp(camera.rotation.x, -PI/4, PI/4)
  20.  
  21. if Input.is_action_just_pressed("ui_cancel"):
  22. get_tree().quit()
  23.  
  24.  
  25. func _physics_process(delta: float) -> void:
  26. # Add the gravity.
  27. if not is_on_floor():
  28. velocity.y -= gravity * delta
  29.  
  30. # Handle Jump.
  31. if Input.is_action_just_pressed("ui_accept") and is_on_floor():
  32. velocity.y = JUMP_VELOCITY
  33.  
  34. # Get the input direction and handle the movement/deceleration.
  35. # As good practice, you should replace UI actions with custom gameplay actions.
  36. var input_dir := Input.get_vector("left", "right", "forward", "back")
  37. var direction := (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
  38. if direction:
  39. velocity.x = direction.x * SPEED
  40. velocity.z = direction.z * SPEED
  41. else:
  42. velocity.x = move_toward(velocity.x, 0, SPEED)
  43. velocity.z = move_toward(velocity.z, 0, SPEED)
  44.  
  45. move_and_slide()
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement