2D platformer Running

So I am trying to code a run button in my game where you hold the run button and you run and if you let go you stop and return to normal walking speed.

I came up with some code that is basically when the player holds the run button it times the speed by 2.0 and changes the animation to running and when they let go it stops and returns to the normal speed. (which is 500) I’ve tried this code and it’s not working so I came here to see if anyone knows how to fix this or if I should instead have running be a true or false state.

func _process(delta):
	if Input.is_action_pressed("run"):
	speed * 2.0
	$AnimatedSprite2D.play("gailrun")
	else:
		speed = 500

What do you mean by its not working? Do you get errors? Does the input not get detected? Does your character not respond? Does the running not end? Tell us what you expected and what actually happens and we will be able to help.

And yes, you should have a state somewhere. Not a Boolean for running or walking or jumping, but something that actually tells you the state that you can respond to.

Something like:

enum State {
   WALKING,
   RUNNING,
   JUMPING,
}
var current_state:State = State.WALKING

# Use it like this:
if current_state == State.RUNNING:
   # do running
elif current_state == State.WALKING:
  # do walking

Thank you by the way (after putting in your code) my error was “Expected indented block after “if” block.”

It doesn’t let me run the scene at all.

The issue with your original code is that you need to assign the value of speed, so speed *= 2.0.

As for the issue with the example code, that’s because you need to replace the comments they left with your own logic.

EDIT: And if it still does not work, make sure you have a keybind set in your Project Settings → Input Map for run.

Indented code after if means you need an indent in the lines that apply if the if is true.

func _process(delta):
	if Input.is_action_pressed("run"):
		#Tabs here:
		speed * 2.0
		$AnimatedSprite2D.play("gailrun")
	else:
		speed = 500

I saw that but assumed it was a copy/paste error.

Edit:
Oh did you mean my code? That was just illustrative.

Edit 2:
@Kynji Oh yes. I missed that! That probably was the issue.