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.
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.