# 1.找到大小

``````magnitude = sqrt(x*x + y*y + z*z)
``````

``````magnitude = sqrt(1*1 + 2*2 + 3*3)
= 3.7416573868
``````

# 2. Find the heading

Next, to find the heading, notice that we just care about rotation about the XZ plane, and we don't care about the Y-axis at all. If we were to "flatten" the 3D space into 2D, it becomes trivial to find the heading.

We can draw a triangle that forms a 90 degree angle with the X-axis (red triangle) and then calculate that angle. Recall from trigonometry `tan(angle) = opposite / adjacent`, and solving for `angle`, we get `angle = arctan(opposite / adjacent)`.

In this case "adjacent" is a known quantity (`redAdjacent = x = 1`), and "opposite" is known too (`redOpposite = z = 3`). Instead of using arctan to solve the equation though, we want to use atan2 since it'll handle all the different cases of x and y for us.

So we have:

``````heading = atan2(redOpposite, redAdjacent)
``````

Plugging in our actual values:

``````heading = atan2(3, 1)
= 1.249045772398
``````

so our heading is `1.249` rad, or ~`72°`.

# 3. Find the pitch

Finally we need to find the pitch. Similarly to what we did with the heading, we can flatten the the 3D space into 2D along the plane that contains these three points: (A) the origin `(0,0,0)`, (B) our point `(1,2,3)`, and (C) our point as it would project onto the XZ plane `(1,0,3)` (e.g. by setting 0 for the Y-value).

If we draw a triangle between all 3 of these points, you will notice that they form a right-triangle again (green triangle). We can simply calculate the angle using `arctan2` again.

We already calculated the green hypotenuse in step 1 (i.e. the magnitude of our vector):

``````greenHypotenuse = sqrt(x*x + y*y + z*z)
= 3.7416573868
``````

We also know the opposite of the green triangle is the same as the y-value:

``````greenOpposite = y
= 2
``````

``````greenOpposite^2 + greenAdjacent^2 = greenHypotenuse^2
y*y + greenAdjacent^2 = x*x + y*y + z*z
greenAdjacent^2 = x*x + z*z
greenAdjacent = sqrt(x*x + z*z)
``````

``````redHypotenuse^2 = redAdjacent^2 + redOpposite^2
= x*x + z*z
redHypotenuse = sqrt(x*x + z*z)
``````

``````greenAdjacent = sqrt(1*1 + 3*3)
= 3.1622776602
``````

``````pitch = atan2(greenOpposite, greenAdjacent)
= atan2(2, 3.1622776602)
= 0.563942641356
``````

0 条评论