Godot Version
v4.4.1.stable.official [49a5bc7b6]
Question
Here is the code for a basic first person character movement.
Can somebody please tell me how to modify it so my character can move in the air depending on which direction is camera facing? (Similar to “Walk Navigation” in Blender)
extends CharacterBody3D
const SPEED = 8.0
const JUMP_VELOCITY = 4.5
const SENSITIVITY = 0.01
@export var head: Node3D
@export var camera_3d: Camera3D
@export var hold_ray: RayCast3D
func _ready() -> void:
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func _unhandled_input(event: InputEvent) -> void:
if event is InputEventMouseMotion and !hold_ray.holding_rotating:
head.rotate_y(-event.relative.x * SENSITIVITY)
camera_3d.rotate_x(-event.relative.y * SENSITIVITY)
camera_3d.rotation.x = clamp(camera_3d.rotation.x,deg_to_rad(-90),deg_to_rad(90))
func _physics_process(delta: float) -> void:
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta
# Handle jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var input_dir := Input.get_vector("left", "right", "forward", "back")
var direction := (head.global_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()
Also here is node tree of my character for reference.