Skip to content

Instantly share code, notes, and snippets.

@NovemberDev
Last active April 25, 2020 02:12
Show Gist options
  • Save NovemberDev/a95001dbed7b381fdcfa259fbab8905d to your computer and use it in GitHub Desktop.
Save NovemberDev/a95001dbed7b381fdcfa259fbab8905d to your computer and use it in GitHub Desktop.
#
# Author: @November_Dev
#
# This class is a straightforward, zero overhead implementation of
# very basic FPS controls.
#
# Ideal node setup:
# KinematicBody
# |- Camera
#
extends KinematicBody
# horizontal rotation (y)
var yaw = 0
# vertical rotation (x)
var pitch = 0
# listen to every input
func _input(event):
# filter events for mouse movement
if event is InputEventMouseMotion:
# float modulus the angle difference,
# so that 360%360==0 and 90%360==90
# to prevent angles above 360 degrees
yaw = fmod(yaw - event.relative.x, 360)
# do the same, but clamp it at 70 and -70
pitch = max(min(pitch - event.relative.y, 70), -70)
# set rotation of the player
rotation_degrees.y = yaw
# set rotation of the camera
$Camera.rotation_degrees.x = pitch
# prepare the variables
func _ready():
pitch = rotation_degrees.x
yaw = $Camera.rotation_degrees.y
# execute every frame
func _physics_process(delta):
# movement direction
var direction = Vector3()
# get a key
if Input.is_key_pressed(KEY_W):
# basis.z is the current forward vector
direction -= global_transform.basis.z
if Input.is_key_pressed(KEY_S):
direction += global_transform.basis.z
if Input.is_key_pressed(KEY_A):
# basis.x is the current.left vector
direction -= global_transform.basis.x
if Input.is_key_pressed(KEY_D):
direction += global_transform.basis.x
# apply movement towards the direction
move_and_slide(direction * 200.0 * delta)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment