Getting stumped by vectors and quaternions

I think I had a tenuous grasp on moving/rotating stuff at one point, but after doing a bunch of GUI work and coming back to it I don’t understand a thing. For instance, I want a 2d sprite to rotate to face the cursor, and the code that usually gets mentioned is something like this:

Vector3 direction = targetPoint - transform.position;
transform.eulerAngles = new Vector3(0, 0, Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg);

First of all, I basically understand why subtracting a vector from another gives you a direction, since they’re points in space, but I have a hard time picturing how it works when magnitude is involved. Also, I was always confused at how to tell which one to subtract from which.

The math in the eulerAngles assignment is just gibberish to me.

How does a Unity programmer typically get comfortable with this stuff? Is there a book with a good in-depth chapter on it, and not just “paste this code into your game?”

Any good high school physics text will have a chapter on vector math. Most game programming books will also have a similar chapter.

Vectors can be visualised as a direction from the origin to the point in space. Adding vectors is simply a case of putting the lines end to end and seeing where it turns up. Subtracting vectors is similar, except the negative vector runs in the opposite direction.

Subtraction is always done as final - initial. So if I have points A and B, and I want to get from A to B, I do B - A.

There are some pictures on the Wikipedia page

  • ‘magnitude’ is just the length of the vector. For angle calculations we typically don’t care. We only care about the direction.
  • When doing a subtraction of vectors like A - B, the resulting vector points in the direction of A, so you pick the order depending on which way you want a vector to point.
  • Mathf.Atan2(y, x) * Mathf.Rad2Deg is used a lot in the 2D calculations. Using the ‘x’ and ‘y’ of a vector, it tell the angle of that vector from Vector3.right (going in a counter-clockwide direction). I believe the actual values go from -180 to 180. Note the order of the parameters. It is ‘y’ first then ‘x’. I personally tend to give answers using Atan2() for 2D questions because some uses of Quaternions tend to flip the object. That is, the objects points in the correct direction, but it is also rotated 180 degrees.

You can get vector basics from a chapter or two on vectors from a math textbook, and I sure there are extensive web pages on vectors on the web. Almost anything you read in a textbook will be usable with Unity.