From Test-Scratch-Wiki

While programming, it is sometimes necessary to find the **direction a 角色 should point given two 速度**
** (x and y). This article presents the 程式 that will provide the correct direction as well as an explanation of how it works.**

## The Script

如果 <(y-vel) = [0]> 那麼 如果 <(x-vel) < [0]> 那麼 面朝 (-90 v) 度 面朝 (90 v) 度 end 如果 <(y-vel) > [0]> 那麼 面朝 ([atan v] 數值 ((x-vel) / (y-vel))) 度 面朝 ((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 菱形积木) 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 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