jueves, 21 de mayo de 2026

Basic Movement System: Walk, Run & Dash (Cooldown) — Godot

 


extends CharacterBody2D

var speed = 150
var run_speed = 300
var dash_speed = 1000
var dash_distance = 500
var is_dashing = false #estado
var can_dash = true #estado
var dash_cooldown = 1
var dash_direction = Vector2.ZERO


func _physics_process(_delta):

	var direction = Vector2.ZERO

	direction.x = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")

	direction.y = Input.get_action_strength("ui_down") - Input.get_action_strength("ui_up")

	direction = direction.normalized()

	var current_speed = speed
	
	if is_dashing:
		current_speed = dash_speed
	elif Input.is_action_pressed("ui_accept"):
		current_speed = run_speed
		$Sprite2D.scale = Vector2(1.2, 1.2)
	else:
		$Sprite2D.scale = Vector2(1, 1)

	velocity = direction * current_speed
	
	if Input.is_action_just_pressed("Dash") and not is_dashing: start_dash()

	move_and_slide()

	look_at_mouse()

func look_at_mouse():

	var mouse_position = get_global_mouse_position()
			
	if mouse_position.x < global_position.x:
		$Sprite2D.flip_h = true
	else:
		$Sprite2D.flip_h = false

func start_dash():
	
	if not can_dash:
		return 
		
	is_dashing = true
	can_dash = false
	
	dash_direction = velocity.normalized()
	if dash_direction == Vector2.ZERO:
		dash_direction = Vector2.RIGHT # fallback
		
	var dash_time = float(dash_distance) / float(dash_speed)
	var timer = get_tree().create_timer(dash_time)
	
	while timer.time_left > 0:
		velocity = dash_direction * dash_speed
		await get_tree().process_frame
	
	is_dashing = false
	
	await get_tree().create_timer(dash_cooldown).timeout
	can_dash = true