Direct3D Geometry: two-vector rotation matrix
Given two 3D vectors A and B, I need to get a rotation matrix that rotates from A to B.
This is what I came up with:
- Derive cosine from
acos(A. B) - Output sine from
asin(| A x B | / (| A | * | B |)) - Use A x B as axis of rotation
- Use the matrix shown at the bottom of this page (axis angle)
This works great except for the 0 ° turns. (which I ignore) and 180 ° (which I consider as a special case). Is there a more graceful way to do this using the Direct3D library? I'm looking for a specific Direct3D answer.
Edit: removed acos and asin (see Hugh Allen's post )
source to share
This is probably more of a typo than a thinking, but acos (AB) is an angle, not its cosine. Similarly for point 2.
You can calculate sin from cos using sin ^ 2 + cos ^ 2 = 1. That is, sin = sqrt (1-cos * cos). This will be cheaper than the vector expression used, and will also eliminate the special cases for 0/180 degrees.
source to share
No, you are pretty much doing it your best. I don't think there is a built-in DirectX feature that does what you want. For step 4, you can use D3DXMatrixRotationAxis()
. Just be careful with edge cases like when | A | or | B | is zero or when the angle is 0 ° or 180 °.
source to share