Skip to content

Instantly share code, notes, and snippets.

@Frontrider
Created March 18, 2023 01:13
Show Gist options
  • Save Frontrider/eb49ee2ac62b702253180a8751641fc9 to your computer and use it in GitHub Desktop.
Save Frontrider/eb49ee2ac62b702253180a8751641fc9 to your computer and use it in GitHub Desktop.
Godot 4 FPS controller
extends RigidBody3D
@export var speed:float = 10.0
@export var jump_force = 5.0
@onready var camera:Camera3D = $Camera3D
@onready var ground_sensor:RayCast3D = $GroundSensor
func _ready():
pass
func _physics_process(delta):
var motion = Vector3()
if Input.is_action_pressed("move_forward"):
motion.x += 1
if Input.is_action_pressed("move_backwards"):
motion.x -= 1
if Input.is_action_pressed("move_left"):
motion.z -= 1
if Input.is_action_pressed("move_right"):
motion.z += 1
motion = motion.rotated(Vector3.UP,camera.rotation.y+PI/2)
if ground_sensor.is_colliding():
move_and_collide(Vector3(motion.x,0,motion.z)*delta*speed)
else:
move_and_collide(Vector3(motion.x,0,motion.z)*delta*speed/2)
func _input(event):
if event.is_action_pressed("jump"):
if ground_sensor.is_colliding():
apply_central_impulse(Vector3(0,jump_force,0))
pass
pass
pass
extends Camera3D
# cam look.
#Only moves the camera if the mouse is captured.
@export var minLookAngle : float = -90.0
@export var maxLookAngle : float = 90.0
@export var lookSensitivity : float = 0.5
var mouseDelta : Vector2 = Vector2()
func _ready():
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
func _input(event):
if Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
# did the mouse move?
if event is InputEventMouseMotion:
mouseDelta = event.relative
if event.is_action_pressed("unlock_mouse"):
if Input.mouse_mode != Input.MOUSE_MODE_CAPTURED:
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
else:
Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
func _process(delta):
if Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
# rotate camera along X axis
rotation_degrees -= Vector3(rad_to_deg(mouseDelta.y), 0, 0) * lookSensitivity *delta
# clamp the vertical camera rotation
rotation_degrees.x = clamp(rotation_degrees.x, minLookAngle, maxLookAngle)
# rotate player along Y axis
rotation_degrees -= Vector3(0, rad_to_deg(mouseDelta.x), 0) * lookSensitivity *delta
mouseDelta = Vector2.ZERO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment