How to make an object face another object in 3D space?

1.1k Views Asked by At

I have a question that maybe it is an easy calculation but I am a motion graphic designer not a Math guy so... here it goes. I have a 3D scene with a perspective camera in it. I want to make a 2D object in the scene to rotate on Y axis to always look in the direction of the camera so from the Camera point of view it won't be visible as a 2D object.

So I can get the values of camera X and Z position and use them to calculate the Y rotation but I am not sure what is the math I should do.

currently I want to leave camera Y position (height) out of it.

I am attaching some photos to maybe make it clearer: Pos1 Pos2 Pos3

Thanks in advance.

2

There are 2 best solutions below

0
On

As David K already suggested you can use atan2 funtion.

It's a special version of arcus tangens that takes into account all possible ranges and signs of input values and returns an angle.

Just compute a vector from your rotating object to target (Camera) and put its X and Y into an atan2 function. The result will be a rotation angle, in Radians.

0
On

That's basic linear algebra.

We use only X,Z cohordinates so we are working in the Euclidean plane $\mathbb R^2$.

Put the origin in the point where the axis of your 2d object is placed. And works in such cohordinates. In practice if $(X_0,Z_0)$ are the cohordinates of the 2d object you use coordinates $(X-X_0,Z-Z_0)$ instead of $(X,Z)$.

Now some Thery:

In $\mathbb R^2$ linear transformations that fixes the origin (and a rotation is one of them) are determined by $2\times 2$ matrices.

Consider points $e_1=(1,0)$ and $e_2=(0,1)$. Then the matrix $\begin{pmatrix} a & b\\ c & d\end{pmatrix}$ sends $e_1$ to point $(a,c)$ and $e_2$ to point $(b,d)$.
And in general $\begin{pmatrix} a & b\\ c & d\end{pmatrix}\begin{pmatrix} x \\ y \end{pmatrix}=\begin{pmatrix} ax + by\\ cx+ dy\end{pmatrix}$, where $\begin{pmatrix} x \\ y \end{pmatrix}$ is another way to say $(x,y)$. (see here for more details on matrix multiplication)

The nice fact is that the images of $e_1$ and $e_2$ determines the matrix.

Now your case.

Start with your object facing the point $(1,0)$, so the camera is on a point $(X,0)$ with $X>0$. If the camera move to point $(X,Z)$ you want to rotate the object so taht it faces the camera, which is the same that facing the normalized pont $(\frac{X}{\sqrt{X^2+Z^2}}, \frac{Z}{\sqrt{X^2+Z^2}})$ that we denote by $(\bar X,\bar Z)$.

So you want a matrix $M$ so that $M e_1=(\bar X,\bar Z)$ and that maps $e_2$ to the normal to $(\bar X,\bar Z)=(-\bar Z,\bar X)$. This matrix is simply

$$M=\begin{pmatrix}\bar X & -\bar Z\\ \bar Z&\bar X\end{pmatrix}$$

The matrix $M$, which you see it depends on $X,Z$ will rotate your object as desired.