While programming, it is sometimes necessary to find the direction a sprite should point given a 2D velocity (x and y components). Many programming languages provide a function called atan2 (2-argument arctangent) to find the angle of a 2D vector, however Scratch doesn't have this. This article presents the script that will provide the correct direction as well as an explanation of how it works.
The Script
point in direction (([atan v] of ((x velocity) / ((y velocity) + (0)))) + ((180) * <(y velocity) < (0)>))
How it Works
| In mathematics, angles are conventionally measured "east-counterclockwise". Scratch's trigonometry blocks behave like this. Sprite directions however are bearings measured "north-clockwise". The script is implemented with this in mind, but is simplified so the conversions are not explicitly shown. |
The mathematical function "atan" (which stands for "arctangent") is the inverse of tangent, a trigonometric function used to determine the ratio of the two legs of a right triangle. The script treats the x and y axes as the two legs of a right triangle, using atan to derive the angle:
([atan v] of ((x velocity) / (y velocity)))
As Scratch's atan only outputs angles between -90° and 90°, half of the directions are in the opposite direction. The second part of the script conditionally rotates by 180° when velocity is less than 0:
((180) * <(y velocity) < (0)>)
In Scratch, a boolean is converted to numbers 0 or 1 for false and true, respectively. The above code therefore results in 180 when velocity is less than 0, and 0 otherwise.
Adding the two parts together produces a direction usable by the point in direction () block.
Finally, it must be mentioned that the shown script adds 0 to the y component. This is intentional to avoid an edge case where a "negative zero" produces an undesired result here. The specifics of this quirk require a large explanation. In essence, the addition makes the zero always positive. For more information, see atan2 edge case tests.
Example Uses
- Finding out the direction the mouse is moving in
- Predicting the position of the character in a platformer in a few seconds, maybe as a power-up tool.
- Finding the direction an arrow should point in given an x and y velocity