I'm trying to make the sprite snap to rotations of 45º (8 directions/top down game). Currently I'm doing this as a quick hack to get what I want:

if k_left and k_down:		sprite_angle = -45
elif k_left and k_up:		sprite_angle = -135
elif k_right and k_down: 	sprite_angle = 45
elif k_right and k_up:		sprite_angle = 135
elif k_down:				sprite_angle = 0
elif k_up:					sprite_angle = 180
elif k_left:				sprite_angle = -90
elif k_right:				sprite_angle = 90
get_node("Sprite").set_rotd( sprite_angle +180 ) # +180 because I've drawn the sprite facing up

I can kind of live with it, but I'd like to have it in less lines of code if I could, but I'm being unable to get my head around how to make it so.

You could have a Vector2 for each key in a map and get a sum of Vectors according to the keys that were pressed. Then using the angle functions of Vector2 you should be able to get the angle you want. http://docs.godotengine.org/en/stable/classes/class_vector2.html#class-vector2-angle You might have to make sure if you get the angle in the same unit you are using, otherwise you have to convert the results before using them.

Not sure if it's the best way, since there are more calculations involved and not that many lines of code saved, but on the other hand using those Vector2 will make it easy in case you want to add analog stick support later on.

Finally done it, using a vector for the direction based on the keys, like you said. I had tried this several times before but for some reason I couldn't get it to work. Maybe I wasn't adding the angles correctly, or maybe I was failing to move the player in the correct direction.

I'm now even using the speed to scale velocity along the angle, which also gives me the good old 8 directions movement.

velocity *= friction
if dir.x or dir.y:
	var angle = dir.angle()
	velocity = Vector2(sin(angle), cos(angle)) * (velocity.length()+accel)

Thanks.

EDIT: this also solves another problem: the player no longer moves faster diagonally.

For 8-directional movement I usually do:

var vect = Vector2()
vect.x = Input.is_action_pressed("right") - Input.is_action_pressed("left")
vect.y = Input.is_action_pressed("down") - Input.is_action_pressed("up")
vect = vect.normalized()

Which gives you a normalized direction vector. You could do that all in one line, but it would be really long.

That's a nice way to simplify it. Do you really need to normalize it, though?

Normalizing fixes the "faster on diagonals" issue.

6 years later