Code for freely moving in the air corresponding to where the camera is looking at?

Godot Version

4.3

Question

I got the code for moving a character with A,S,D,W just like in 3D First Person Shooter:

		var input_dir : Vector2 = Input.get_vector("left", "right", "up", "down" )
						
		var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
		if direction:
			velocity.x = move_toward(velocity.x, direction.x * MAX_HSPEED * delta, HACCELERATE * delta)
			velocity.z = move_toward(velocity.z, direction.z * MAX_VSPEED * delta, VACCELERATE * delta)

Now, I would like to be able to move freely in the air just like being a ghost observer in First Person Shooter. You can look around with your camera, then pressing forward will now make you fly upward or downward in 3D space as well. What is the code for this?

You are close, you need to take into account the basis of the camera instead of the player.
Make sure to get the correct camera reference, and make a variable for the vertical speed

var input_dir := Input.get_vector("left", "right", "up", "down" )
						
var direction := (%CAMERA.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
    if direction:
	    velocity.x = move_toward(velocity.x, direction.x * MAX_HSPEED * delta, HACCELERATE * delta)
	    velocity.z = move_toward(velocity.z, direction.z * MAX_VSPEED * delta, VACCELERATE * delta)

var vertical_input := 0.0

if Input.is_action_pressed("move_up"):
    vertical_input = 1.0
if Input.is_action_pressed("move_down"):
    vertical_input = -1.0

velocity.y += vertical_input * VERTICAL_MOVE_SPEED

move_and_slide()
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.