Godot Version
godot 4.4
Question
i made a 3d fps movement, but whenever i click one of the buttons to move or esc to chandge the mouse mode, the game chrashes and turns off
here is my script:
extends CharacterBody3D
@export var playerSpeeed = 5.0
@export var jumpForce = 10.0
@export var gravity = 8.0
@export var mouseSensivity = 0.5
@onready var head = $Head
@onready var camera = $Head/Camera3D
var direction = Vector3.ZERO
var camera_x_angel = 0.0
func _ready():
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func _input(event: InputEvent) -> void:
if event is InputEventMouseMotion:
head.rotate_y(-deg_to_rad(event.relative.x * mouseSensivity))
camera_x_angel += event.relative.y * mouseSensivity
camera_x_angel = clamp(camera_x_angel, -90.0, 90.0)
camera.rotation.x = -deg_to_rad(camera_x_angel)
if event is InputEventKey:
if event.scancode == KEY_ESCAPE and event.pressed:
Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
func _process(delta):
direction = Input.get_axis("left", "right") * head.basis.x + Input.get_axis("forward", "backward") * head.basis.z
velocity = direction.normalized() * playerSpeeed + velocity.y * Vector3.UP
func _physics_process(delta: float) -> void:
var input_direction: Vector2 = Input.get_vector("left", "right", "forward", "backward")
var direction: Vector3 = head.basis * Vector3(input_direction.x, 0, input_direction.y)
# you should use a seperate horizontal/vertical velocity so you can preserve gravity
var vertical_velocity := velocity.project(up_direction)
var horizontal_velocity := velocity - vertical_velocity
# assign player movement on a horizontal plane, not overwriting gravity
horizontal_velocity = direction * playerSpeeed
# gravity and jumping, using vertical_velocity
if Input.is_action_just_pressed("jump") and is_on_floor():
vertical_velocity.y += jumpForce
else:
vertical_velocity.y -= gravity * delta
# re-combine horizontal and vertical velocity
velocity = vertical_velocity + horizontal_velocity
move_and_slide()