Gravity increases when mouse moves (3D FPS)

Godot Version

4.6.2.stable (steam)

Question

I’m trying to code for an FPS game but every time my character jumps, it starts flying at an extremely low gravity rate. if i move my mouse, the gravity becomes higher. How do i fix this?

extends CharacterBody3D

const SPEED = 7.0
const JUMP_VELOCITY = 8
const SENSITIVITY =0.005


@onready var head = $Node3D
@onready var camera = $Node3D/Camera3D

var doublejump = false

func _ready():
	for child in $Node3D.find_children("*", "VisualInstance3D") :
		child.set_layer_mask_value(1, false)
		child.set_layer_mask_value(2, true)
	

func _unhandled_input(event):
	if event is InputEventMouseMotion: 
		head.rotate_y(-event.relative.x * SENSITIVITY) 
		camera.rotate_x(-event.relative.y * SENSITIVITY)
		camera.rotation.x =clamp(camera.rotation.x, deg_to_rad(-90), deg_to_rad (90))
 
	
		

	
	if not is_on_floor():
		velocity += get_gravity() * 0.03
	else: doublejump = false
	
	
	if Input.is_action_just_pressed("jump") and (is_on_floor()or !doublejump):
		velocity.y = JUMP_VELOCITY
	
	
		
	
	if Input.is_action_just_pressed("jump") and !is_on_floor(): 
		doublejump = true
	


func _physics_process(_delta: float) -> void:
	var input_dir := Input.get_vector("left", "right", "forward", "backward")
	var direction = (head.transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	if direction:
		velocity.x = direction.x * SPEED
		velocity.z = direction.z * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		velocity.z = move_toward(velocity.z, 0, SPEED)

	move_and_slide()

Apply gravity in _physics_process(), not in _unhandled_input().

Also, you should use the event parameter instead of the Input singleton inside _unhandled_input().
event.is_action_pressed("jump") instead of Input.is_action_just_pressed("jump").

Thank you!

The gravity is fixed but trying to change Input to event seems to make the game crash.

Do you get any error messages?

E 0:00:01:617 _unhandled_input: Invalid call. Nonexistent function ‘is_action_just_pressed’ in base ‘InputEventMouseMotion’.
character_body_3d.gd:32 @ _unhandled_input()
character_body_3d.gd:32 @ _unhandled_input()

Yeah, it should be

event.is_action_pressed()

and not

event.is_action_just_pressed()

Only Input has to differentiate between the action being pressed or just pressed, because it is meant to be used in functions like _physics_process().

_unhandled_input() is only callled when any input happens, so any pressed event is always just pressed.

1 Like

It worked, Thank you!