(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

# Finding Direction With Velocity

While programming, it is sometimes necessary to find the direction an object 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.

## The Script

```if<(y) = (0)>
if<(x) < (0)>
point in direction (-90 v)
else
point in direction (90 v)
end
else
if<(y) > (0)>
point in direction ([atan v] of ((x)/(y)))
else
point in direction ((180)+([atan v] of ((x)/(y))))
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 essentially 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 "asin" 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).