Pointing Z axis at target

I feel stupid for asking this but can someone please explain to me how is this making an object point its Z axis at the target?

74760-untitled1.png

Well, first of all you should have at least a little bit of understanding what a Quaternion is. If you have never heard about them just see this numberphile video which gives you a basic overview.

A quaternion actually represent a relative rotation. However Unity defines the default orientation as the z-axis being forward. So the rotation of an object basically consists of the forward vector given in worldspace and additionally how much the object is rotated around that forward axis.

Quaternion.LookRotation creates a rotation based on a direction vector and a second “hint” vector. This hint vector is used to determine the rotation around the first direction vector. Unity’s default orientation defines this as “up”. If you don’t pass a second vector yourself it defaults to “Vector3.up”. In most cases you don’t need to manually pass an up-vector. Only in some cases where you need to control the “rolling” of the object. 3D space games which often allow free 3D rotation need this for example.

Next thing about your piece of code is the direction vector we talked about. In general for vector math there is the “head-minus-tail” rule to determine a relative vector given two vectors:

if you want a relative direction vector that points from A to B you have to subtract A from B. “A” is the “head” and “B” the “tail” of the arrow.

Since your “head” is your target you have to subract your own position from the target position.

If you want more information you should be more specific.