How can I find objects behind my camera?

569 Views Asked by At

I have got trees in a world. enter image description here

However, these trees can be fairly CPU intensive. As you can see, the far-away island on the left has no trees at all - This is because trees currently have to only render in a short radius of the ship (or lag like hell).

My question is, if I have a single tree, how can I check if that tree is behind the camera?

enter image description here

I have:

The location of the ship.

The location of the tree.

The direction of the Camera.

The size of the tree (sortof).

Basically, I would like to compare the direction (and location) in which the camera is looking and then compare it to the tree's location to see if the tree is in front of or behind the camera.

Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

Having the camera matrix $K$: $$ \begin{bmatrix} f_x & 0 & w/2 \\ 0 & f_y & h/2 \\ 0 & 0 & 1 \\ \end{bmatrix} $$ where $w$ and $h$ are the projection image size, and $f$ is the focal length, and the camera rotation $R$ and translation $t$ then the projection matrix is formed by: $$P=K[R|t]$$ and a word point $X$ represented in homogeneous coordinates is projected in image space as: $$x=PX$$ In order to check if a tree is in front of the camera, all you need to do is to transform the tree (i.e. the center of the tree bounding box $Xt$) from world space in camera space: $$X_c=R*X_t+t$$ and check if the depth value $X_c.z$ is positive.