Godot Version
4.4
Question
Long story short, I’ve recently followed this tutorial on how to make a Third Person Controller in Godot for most of it. It didn’t initially have a jumping mechanic, so I improvised one. I ended up with something like this:
extends CharacterBody3D
@onready var camera_mount: Node3D = $CameraMount
@onready var animation_player: AnimationPlayer = $"Visuals/X Bot/AnimationPlayer"
@onready var visuals: Node3D = $Visuals
var SPEED = 3
const JUMP_VELOCITY = 4.5
const SMOOTH_SPEED = 10.0
var walking_speed = 3.0
var running_speed = 5.0
var running = false
var jumping = false
@export var sens_horizontal = 0.5
@export var sens_vertical = 0.5
func _ready():
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
func _input(event):
if event is InputEventMouseMotion:
rotate_y(deg_to_rad(-event.relative.x*sens_horizontal))
visuals.rotate_y(deg_to_rad(event.relative.x*sens_horizontal))
camera_mount.rotate_x(deg_to_rad(event.relative.y*sens_vertical))
func _physics_process(delta: float) -> void:
if Input.is_action_pressed("Run"):
SPEED = running_speed
running = true
else:
SPEED = walking_speed
running = false
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta
# Handle jump.
if is_on_floor():
if Input.is_action_just_pressed("Jumping"):
velocity.y = JUMP_VELOCITY
jumping = true
else:
jumping = false
# 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", "Backward")
var direction := (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
var visual_dir = Vector3(input_dir.x, 0, input_dir.y).normalized()
if direction:
if jumping:
if animation_player.current_animation != "Jump":
animation_player.play("Jump")
else:
if running:
if animation_player.current_animation != "Running":
animation_player.play("Running")
else:
if animation_player.current_animation != "Walking":
animation_player.play("Walking")
visuals.rotation.y = lerp_angle(visuals.rotation.y, atan2(-visual_dir.x, -visual_dir.z), delta * SMOOTH_SPEED)
velocity.x = -direction.x * SPEED
velocity.z = -direction.z * SPEED
else:
if jumping:
if animation_player.current_animation != "Jump":
animation_player.play("Jump")
else:
if animation_player.current_animation != "Idle":
animation_player.play("Idle")
velocity.x = move_toward(velocity.x, 0, SPEED)
velocity.z = move_toward(velocity.z, 0, SPEED)
move_and_slide()
Which, tbf, works perfectly fine, but I couldn’t help but notice how I can jump mid-walk but not while running—a very basic mechanic in most third persons. I’ve tried everything to get it to work, but I still couldn’t get my character to jump while running.
Does anyone have an idea on how to make my character jump while running? I would appreciate any help atp.