Advertisement
Guest User

Untitled

a guest
Jan 2nd, 2024
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. extends CharacterBody3D
  2.  
  3. var speed
  4. @export var sprint_speed = 4.0
  5. @export var walk_speed = 2.0
  6. @export var jump_velocity = 4.5
  7. @export var gravity = 9.8
  8. @export var sensitivity = 0.004
  9.  
  10. @onready var head = $Head
  11. @onready var camera = $Head/Camera3D
  12.  
  13. #Headbobbing
  14. var bob_freq = 4.5
  15. var bob_amp = 0.04
  16. var t_bob = 0.0
  17.  
  18. #Keeps the cursor within the game - hides it
  19. func _ready():
  20. Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
  21.  
  22. #mouse movement
  23. func _unhandled_input(event):
  24. if event is InputEventMouseMotion:
  25. rotate_y(-event.relative.x * sensitivity)
  26. camera.rotate_x(-event.relative.y * sensitivity)
  27. camera.rotation.x = clamp(camera.rotation.x, deg_to_rad(-40), deg_to_rad(60))
  28.  
  29. func _physics_process(delta):
  30. #this adds gravity
  31. if not is_on_floor():
  32. velocity.y -= gravity * delta
  33.  
  34. #Handles jump / requires player be grounded
  35. if Input.is_action_just_pressed("Jump") and is_on_floor():
  36. velocity.y = jump_velocity
  37.  
  38. #Handles sprinting
  39. if Input.is_action_pressed("Sprint"):
  40. speed = sprint_speed
  41. else:
  42. speed = walk_speed
  43.  
  44.  
  45. #Input direction and handles movement/deacceleration
  46. var input_dir = Input.get_vector("Left", "Right", "Forward", "Back")
  47. var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
  48. if is_on_floor():
  49. if direction:
  50. velocity.x = direction.x * speed
  51. velocity.z = direction.z * speed
  52. else:
  53. velocity.x = lerp(velocity.x, direction.x * speed, delta * 7.0)
  54. velocity.z = lerp(velocity.z, direction.z * speed, delta * 7.0)
  55. else:
  56. velocity.x = lerp(velocity.x, direction.x * speed, delta * 3.0)
  57. velocity.z = lerp(velocity.z, direction.z * speed, delta * 3.0)
  58.  
  59.  
  60. t_bob += delta * velocity.length() * float(is_on_floor())
  61. camera.transform.origin = _headbob(t_bob)
  62.  
  63. move_and_slide()
  64.  
  65. #function actually implements headbob using sine wave
  66. func _headbob(time) -> Vector3:
  67. var pos = Vector3.ZERO
  68. pos.y = sin(time * bob_freq) * bob_amp
  69. pos.x = cos(time * bob_freq / 2) * bob_amp
  70. return pos
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement