While programming, it is sometimes necessary to find the direction a sprite should point given two velocities (x and y). This article presents the script that will provide the correct direction as well as an explanation of how it works.
if <(y-vel) = > then if <(x-vel) < > then point in direction (-90 v) else point in direction (90 v) end else if <(y-vel) > > then point in direction ([atan v] of ((x-vel) / (y-vel))) else point in direction ((180) + ([atan v] of ((x-vel) / (y-vel)))) end end
How it Works
The bottom half calculates the direction working on the assumption that y is not zero (which would yield an error when x is divided by y). The mathematical function "atan" which stands for "Arc Tangent" and is the inverse of tangent, a trigonometric function used to determine the ratio of the two legs of a right triangle.
The script essentially treats the x and y axes as the two legs of a right triangle, using "atan" to derive the angle. However, as the angle has to be between -90 and 90, the "y > 0" conditional (or Boolean Block) must be added to point the sprite in the proper direction.
It is notable that typical geometry uses atan(y/x) (rather than x/y) to determine the angle; the flip made in the script is to match with Scratch's unusual degree measurement system (0 degrees is typically right).
The top half of the script is a simple comparison. If y velocity is zero, the only possible directions — ignoring the chance that the x velocity could be zero — are right and left (90 and -90 degrees). Should both the x and y velocities be zero, the sprite will face right (90 degrees).
- 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