0 votes

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
Godot version 3.2
in Engine by (15 points)

1 Answer

+1 vote
Best answer

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.
by (1,259 points)
selected by

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!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.