Recommend better code for rotating a player

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: 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:

if (input_vector.x == 0 && input_vector.y < 0): # up
elif (input_vector.x > 0 && input_vector.y < 0): # up-right
elif (input_vector.x > 0 && input_vector.y == 0): # right
elif (input_vector.x > 0 && input_vector.y > 0): # down-right
elif (input_vector.x == 0 && input_vector.y > 0): # down
elif (input_vector.x < 0 && input_vector.y > 0): # down-left
elif (input_vector.x < 0 && input_vector.y == 0): # left
elif (input_vector.x < 0 && input_vector.y < 0): # up-left
:bust_in_silhouette: Reply From: skysphr

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:

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:

  1. 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
  2. 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.
  3. Casting the previous value to an integer, so that there are no more in between values
  4. 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!

gdboling | 2021-12-09 15:45