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
.