A little help with Running Code when i hold Shift?

Godot Version

4.4

i tried to make it but i kinda messed it up, i have to press Shift first then A or D for code to switch to running State because i made in controls Shift + A/D instead of i just hold Shift while moving to run and let go to walk heres my code

var speed = Input.get_axis("Walk Left", "Walk Right")
	if speed > 0:
		animated_sprite.flip_h = false
		$Ground.scale.x = 1
		$AirHover.scale.x = 1
		$AirForward.scale.x = 1
		%CollisionShape2D.position.x = -41.0
	elif speed < 0:
		animated_sprite.flip_h = true
		$Ground.scale.x = -1
		$AirHover.scale.x = -1
		$AirForward.scale.x = -1
		%CollisionShape2D.position.x = -261.0
	if  is_on_floor():
		velocity.x = speed * SPEED
		if   speed > 0 or speed < 0:
			current_state = States.WALKING
	if Input.get_axis("Run Left", "Run Right") and is_on_floor():
		velocity.x = speed * RSPEED
		if   speed > 0 or speed < 0:
			current_state = States.RUNNING

how to make that i hold shift run and let go get back to walking

Well, it’s better to make an action “Run” with only the key Shift instead because that makes the code easier to write.
And then swap out this:

if  is_on_floor():
	velocity.x = speed * SPEED
	if   speed > 0 or speed < 0:
		current_state = States.WALKING
if Input.get_axis("Run Left", "Run Right") and is_on_floor():
	velocity.x = speed * RSPEED
	if   speed > 0 or speed < 0:
		current_state = States.RUNNING

For this:

if is_on_floor():
	var running: bool = Input.is_action_pressed("Run")
	var move_speed: float = RSPEED if running else SPEED
	velocity.x = speed * move_speed
	if speed != 0:
		current_state = States.RUNNING if running else States.WALKING
In general, you should try to repeat yourself as little as possible

For example, this:

if speed > 0:
	animated_sprite.flip_h = false
	$Ground.scale.x = 1
	$AirHover.scale.x = 1
	$AirForward.scale.x = 1
	%CollisionShape2D.position.x = -41.0
elif speed < 0:
	animated_sprite.flip_h = true
	$Ground.scale.x = -1
	$AirHover.scale.x = -1
	$AirForward.scale.x = -1
	%CollisionShape2D.position.x = -261.0

is mostly just the same block of code, duplicated twice for the different cases. A “cleaner” solution would be this:

if speed != 0:
	animated_sprite.flip_h = speed < 0
	$Ground.scale.x = sign(speed)
	$AirHover.scale.x = sign(speed)
	$AirForward.scale.x = sign(speed)
	%CollisionShape2D.position.x = -261.0 if speed < 0 else -41.0
1 Like

Code working pretty good tysm, also thanks for cleaning flipping code, I’m trying to learn coding xD