Skip to content

Instantly share code, notes, and snippets.

@Oppodelldog
Last active December 17, 2023 18:39
Show Gist options
  • Save Oppodelldog/d462c9264895758da3fff9c00bdc3301 to your computer and use it in GitHub Desktop.
Save Oppodelldog/d462c9264895758da3fff9c00bdc3301 to your computer and use it in GitHub Desktop.
some 3d character controller script for godot engine
extends CharacterBody3D
## forward/backward speed
@export var zSpeed = 320
## left/right speed (strafe)
@export var xSpeed=380.5
## speed downwards when falling
@export var ySpeed = 275
## mouse sentitivity for horizontal mouse movement (player rotation around Y)
@export var mouseHSensitivity=0.1
## mouse sensitivity for vertical mouse movement (camera rotation around X)
@export var mouseVSensitivity=0.1
## maximum vertical camera rotation
@export var cameraRotMax=0.1
## minimum vertical camera rotation
@export var cameraRotMin=-1.2
## If is no more mouse movement after this number of seconds, mouse inputs is reset.
## This prevents the camera from rotating endlessly.
@export var mouseResetDelay=0.1
var camPivot:Marker3D # "$CameraPivot" holds the camera
var pivot:Marker3D # "$Pivot" holds the mesh
var yRot:int
var xRot:int
var noMouseInputSince:float
func _ready():
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
camPivot=($CameraPivot as Marker3D)
pivot=$Pivot
func _input(event):
if event is InputEventMouseButton:
if event.button_index==1:
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
if event is InputEventMouseMotion:
yRot=-event.relative.x*mouseHSensitivity
xRot=-event.relative.y*mouseVSensitivity
noMouseInputSince=0
if event is InputEventKey:
if event.physical_keycode==KEY_ESCAPE:
Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
func dirX():
if Input.is_action_pressed("move_right"):
return 1
if Input.is_action_pressed("move_left"):
return -1
return 0
func dirZ():
if Input.is_action_pressed("move_back"):
return 1
if Input.is_action_pressed("move_forward"):
return -1
return 0
func resetMouseInput(delta):
noMouseInputSince+=delta
if noMouseInputSince>mouseResetDelay:
yRot=0
xRot=0
func applyMouseInput(delta):
rotation.y+=yRot*delta
camPivot.rotation.x+=xRot*delta
camPivot.rotation.x=clampf(camPivot.rotation.x,cameraRotMin,cameraRotMax)
func applyMovement(delta):
var vx = transform.basis.x * dirX() * xSpeed * delta
var vz = transform.basis.z * dirZ() * zSpeed * delta
velocity = vx+vz
func _physics_process(delta):
resetMouseInput(delta)
if not is_on_floor():
velocity.y = -ySpeed * delta
move_and_slide()
else:
applyMovement(delta)
applyMouseInput(delta)
move_and_slide()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment