Double press to run

Godot Version

4.3

Question

Hello, i’m making a hack and slash but in 2d, I’m trying to implement the running when the player double press but every single press the player runs and then few seconds walks, anyone explains what’s wrong and how do i fix it?

extends CharacterBody2D

const SPEED = 300.0
const RUN_SPEED = 500.0
const DOUBLE_TAP_TIME = 0.3 # Time window for double-tap detection

@onready var animation = $AnimatedSprite2D

var last_direction_x = 0
var last_tap_time_x = -1.0
var is_running = false

func _physics_process(delta):
var direction_x = Input.get_axis(“ui_left”, “ui_right”)
var direction_y = Input.get_axis(“ui_up”, “ui_down”)
var current_time = Time.get_ticks_msec() / 1000.0

# Update running state based on horizontal movement
if direction_x != 0:
	if last_direction_x == direction_x:
		# Same direction pressed, check for double-tap
		if last_tap_time_x > 0 and current_time - last_tap_time_x < DOUBLE_TAP_TIME:
			is_running = true
		else:
			is_running = false
	else:
		# New direction pressed
		is_running = false
		last_tap_time_x = current_time  # Record the time of the first tap

	last_direction_x = direction_x
else:
	# No horizontal input
	is_running = false
	last_direction_x = 0
	last_tap_time_x = -1.0

# Update velocity based on running state
if direction_x != 0:
	velocity.x = direction_x * (RUN_SPEED if is_running else SPEED)
	animation.play("run" if is_running else "walk")
else:
	velocity.x = 0
	if direction_y == 0:
		animation.play("idle")

# Handle vertical movement
if direction_y != 0:
	velocity.y = direction_y * SPEED
else:
	velocity.y = 0

move_and_slide()

# Flip sprite based on horizontal direction
if direction_x > 0:
	animation.flip_h = false
elif direction_x < 0:
	animation.flip_h = true