Godot Version
4.5.1
Question
Jump not working in 3D game
Hi all,
I started with a 3D player that could jump, move forward, back and sideways, the standard when you select the Basic Movement template script.
After some struggle I was able to implement camera rotation with mouse and replace the sideways “crab” moves with rotation moves, which is what I wanted, but now jump stopped working and I cant figure why.
Any ideas?
extends CharacterBody3D
const MOVE_SPEED = 5.0
const ROTATION_SPEED = 2.5
const JUMP_VELOCITY = 4.5
const gravity = 9.8
var rotation_direction: float = 0
var move_direction: float = 0
# Declare camera and arm nodes as variables
@onready var camera := $SpringArm3D/Camera3D
@onready var arm := $SpringArm3D
# Input funcion to control arm and camera rotation
func _input(event: InputEvent) -> void:
if event is InputEventMouseButton:
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
# If ESC is pressed, no longer captures mouse movement, until it moves again (?)
elif event.is_action_pressed("ui_cancel"):
Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
# If mouse movement is captured
if Input.MOUSE_MODE_CAPTURED:
if event is InputEventMouseMotion:
# Rotates one axis relative to the other
arm.rotate_y(-event.relative.x*0.005)
camera.rotate_x(-event.relative.y*0.005)
# Gives a limit to the rotation, so that it doesnt rotates non stop
camera.rotation.x = clamp(camera.rotation.x, deg_to_rad(-60), deg_to_rad(60))
func _process(_delta: float):
# Get rotation input (left/right keys)
rotation_direction = Input.get_axis("move_left", "move_right")
# Get movement input (forward/backward keys)
move_direction = Input.get_axis("move_backward", "move_forward")
func _physics_process(delta: float):
# Add the gravity.
if not is_on_floor():
velocity.y -= gravity * delta
# Handle jump.
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Apply rotation
if rotation_direction != 0:
# Rotate around the global Y axis
rotate_y(-rotation_direction * ROTATION_SPEED * delta)
# Apply movement in the character's forward direction (local -Z axis by default)
if move_direction != 0:
# Get the character's current forward vector (basis.z points backward, so use -basis.z for forward)
var forward_vector: Vector3 = -global_transform.basis.z.normalized()
velocity = forward_vector * move_direction * MOVE_SPEED
else:
velocity = Vector3.ZERO
# Move the character
move_and_slide()