Need help with dash bug

Godot Version

Godot 4.2.1
Hi, I’m a beginner in Godot and I’m having an issue.

So I was creating an 8 directional dash system for a 2d platformer game and there’s this one bug that made me scratch my hair.

So what I expected is when player pressed D following by A or the opposite and hold both key then dash, they dashed to the direction of the last pressed key. For example, If I press D then I press A, I will dashed to A direction (Left)

What actually happened here is, they always dashed to left (A) even though I pressed A then D and hold it

Here’s a snippet of my code

@export var dash_speed = 320.0
@export var dash_duration_time = 0.2
@export var dash_cooldown_time = 1.0

@onready var dash_duration = $dash_duration
@onready var dash_cooldown = $dash_cooldown

var can_dash = true
var is_dashing = false
var dash_direction = Vector2.RIGHT
var last_pressed_direction = 0

func _physics_process(delta: float) -> void:
	handle_dash()

func handle_dash():
	if Input.is_action_just_pressed("dash") && can_dash && !is_dashing:
		is_dashing = true
		can_dash = false
		
		# Determine dash direction
		var input_dir = Vector2.ZERO
		if Input.is_action_pressed("right"):
			input_dir.x = 1
			last_pressed_direction = 1
		if Input.is_action_pressed("left"):
			input_dir.x = -1
			last_pressed_direction = -1
		if Input.is_action_pressed("down"):
			input_dir.y = 1
		if Input.is_action_pressed("up"):
			input_dir.y = -1

		# Resolve correct dash direction
		if input_dir == Vector2.ZERO:
			dash_direction = Vector2.LEFT if sprite.flip_h else Vector2.RIGHT
		else:
			# Prioritize the most recently pressed horizontal direction
			if Input.is_action_just_pressed("left") or (Input.is_action_pressed("left") and last_pressed_direction == -1):
				input_dir.x = -1
			elif Input.is_action_just_pressed("right") or (Input.is_action_pressed("right") and last_pressed_direction == 1):
				input_dir.x = 1
			dash_direction = input_dir.normalized()
		perform_dash()

func perform_dash():
	velocity = dash_direction * dash_speed
	dash_duration.start()

func _on_dash_duration_timeout():
	if is_dashing:
		is_dashing = false
		velocity = Vector2.ZERO
		dash_cooldown.start()

func _on_dash_cooldown_timeout():
	can_dash = true

Thank you!

The problem is that you’re computing last direction like this:

if Input.is_action_pressed("right"):
    input_dir.x = 1
    last_pressed_direction = 1
if Input.is_action_pressed("left"):
    input_dir.x = -1
    last_pressed_direction = -1

which means you first check for right, then for left. If you press both keys, since left is checked in a second place, it will always be prioritize.
To ensure this is what’s causing the issue, try to swap the conditions; your dash should then always go to the right.

Feel free to ask again if you need some help on how to fix that!

1 Like