Transition from walking to running

Hi!
I’m having trouble switching from walking to running. My code is working perfectly right now, but I want to add the ability to run by pressing Shift + WASD. When I press those keys, I want to increase the character’s speed and play a special running animation using AnimationPlayer.
But I’m a little confused about how to properly handle the input. Currently, the Player.gd script reads WASD key inputs in the _physics_process function to control the character’s walking. And the PlayerWalkState.gd state detects movement if it’s not equal to 0.
How can I implement running? Am I correct in thinking that I need to add new Shift + WASD values to the InputMap? But in that case, how do I detect movement in Player.gd? What should I pass to Input.get_vector()?
I would be very grateful if someone could offer some advice!

Player.gd

class_name Player extends CharacterBody2D


@onready var player_animation_manager: AnimationPlayer = $PlayerAnimationManager

var speed: float = 65.0
var direction: Vector2 = Vector2.ZERO
var last_direction: Vector2 = Vector2.DOWN

func _physics_process(_delta: float) -> void:
	direction = Input.get_vector("move_left", "move_right", "move_up", "move_down")
	
	if direction != Vector2.ZERO:
		last_direction = get_abs_last_direction()

func get_abs_last_direction() -> Vector2:
	var abs_direction: Vector2
	
	if abs(direction.x) > abs(direction.y):
		abs_direction = Vector2.RIGHT if direction.x > 0 else Vector2.LEFT
	else:
		abs_direction = Vector2.DOWN if direction.y > 0 else Vector2.UP
	
	return abs_direction

PlayerWalkState.gd

class_name PlayerWalkState extends PlayerState


const WALK_ANIMATION_PREFIX: String = 'walk'

func physics_update(_delta: float) -> void:
	update_state_animation(WALK_ANIMATION_PREFIX, player.last_direction)

	player.velocity = player.direction * player.speed
	player.move_and_slide()
	
	if player.direction == Vector2.ZERO:
		transitioned.emit(PLAYER_STATES_NAMES.get('IDLE'))

PlayerIdleState.gd

class_name PlayerIdleState extends PlayerState


const IDLE_ANIMATION_PREFIX: String = 'idle'

func enter() -> void:
	update_state_animation(IDLE_ANIMATION_PREFIX, player.last_direction)

func physics_update(_delta: float) -> void:
	if player.direction != Vector2.ZERO:
		transitioned.emit(PLAYER_STATES_NAMES.get('WALK'))

I would simply detect if the player is pressing RUN(shift) and is on floor then change the speed value to be higher but when the player lets go of RUN and is on floor revert to walk speed

2 Likes