The Strange Impact of GDScript Code Order on Execution Results

Godot Version

4.4

Question

  • In the tutorial implementation, specifically at the step “Listening to player input,” I noticed that when running the following code:
extends Sprite2D

var speed = 1
var angular_speed = PI

func _process(delta):
	var direction = 0
	if Input.is_action_pressed("ui_left"):
		direction = -1
	if Input.is_action_pressed("ui_right"):
		direction = 1
	rotation += angular_speed * delta * direction
	var velocity = Vector2.ZERO
	if Input.is_action_pressed("ui_up"):
		velocity = Vector2.UP.rotated(rotation) * speed
	position += speed * velocity
	if Input.is_action_pressed("ui_down"):
		velocity = Vector2.DOWN.rotated(rotation) * speed
	position += speed * velocity
  • The sprite’s movement speed is different when moving up and down. I would like to understand the underlying logic behind this.
  • In the above code, the sprite’s speed when moving up is approximately twice as fast as when moving down.
  • If the order of this part of the code is swapped, the result is reversed:
	if Input.is_action_pressed("ui_down"):
		velocity = Vector2.DOWN.rotated(rotation) * speed
	position += speed * velocity
	if Input.is_action_pressed("ui_up"):
		velocity = Vector2.UP.rotated(rotation) * speed
	position += speed * velocity
  • Hint: The reason for writing “position += speed * velocity” twice is that I found that pressing both the up and down arrow keys simultaneously can make the object remain stationary.

There’s nothing strange, you are adding twice the speed * velocity to the position property independently of which input is being pressed.

If speed is 1.0 then position ended adding (0, 200) to its value

If speed is 1.0 then position ended adding only (0, -100) to its value

1 Like

It’s because you are adding velocity twice:

  • when you press up, velocity is up
  • then if you dont press down, velocity is still down, but you add it to position again.

I’m unsure what should happen if you press both up and down at the same time - imho not moving is the correct result

1 Like

Thanks, I was overthinking it before. I was stuck on the execution order of the code, but now it seems like it’s just executing in the normal sequence.