Topic was automatically imported from the old Question2Answer platform.

Asked By

gdboling

I’m learning 2D gamedev and godot. I started creating an Ikari Warriors clone and I have code that rotates my player by 45 degrees in 8 directions. I like the effect and I don’t want to make it smooth. However, I’m wondering if there is a shortcut way of doing the following:

As long as your input_vector only has 8 possible values, you can simply write set_rotation(input_vector.angle()). If you’re running the code continuously and the input_vector is zeros when there is no input, you might want to wrap it inside an if statement:

if input_vector:
set_rotation(input_vector.angle())

If on the other hand your input vector can have in between angles and you want it to snap to eight directions, you can use

set_rotation(int(input_vector.angle() / TAU * 8) / 8.0 * TAU)

You might find this line of code terribly confusing; I derived it by:

Converting the angle into a floating point between 0 and 1 (angle() returns radians and TAU is 2π, or a full circle): input_vector.angle() / TAU

Multiplying that by 8, so that it is now a floating point between 0 and 8 where 0->1 are angles between 0° and 45°, 1->2 are angles between 45° and 90°, etc. You might want to subtract 0.5 here to make it so that for example 89° goes to north instead of north-east.

Casting the previous value to an integer, so that there are no more in between values

Dividing back by 8.0 (to force casting back to float) and multiplying by TAU to convert into an usable angle for set_rotation.

That’s really helpful. You’re second option almost works. For some reason, moving left keep the rotation at the 135 degree vector. But I think I can figure that out. Thanks!