I'm wrapping my head around OpenGL ES 2.0 and I think I'm trying to do something very simple, but I think the math may be eluding me.

I created a simple, flat-ish cylinder in Blender that is 2 units in diameter. I want to create an arbitrary grid of these edge to edge (think of a checker board).

I'm using a 3D perspective with GLKit:

    CGSize size = [[self view] bounds].size;
    _projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(45.0f), size.width/size.height, 0.1f, 100.0f);

So, I managed to manually get all of these cylinders drawn on the screen just fine. However, I would like to understand how I can programmatically "fit" all of these cylinders on the screen at the same time given the camera location, screen size, cylinder diameter, and the number of rows/columns.

So the net effect is that for small grids (i.e., 5x5) the objects are closer to the camera, but for large grids (i.e., 30x30) the objects are farther away. In either case, all of the cylinders are visible.


There are two ways in which your scene (a grid of cylinders) will outgrow your view port.

  • It can extend beyond the vertical field of view.
  • It can extend beyond the horizontal field of view.

Which one happens first (or is the most restrictive) will depend on:

  • window aspect ratio.
  • camera field of view.
  • ratio of grid dimensions.
  • camera tilt (45 deg in your case.)

If you can make a basic assumption that it will always be the horizontal field-of-view that gets transgressed first, you can skip determining this.

Let's assume we will fit for width (or horizontal field of view.) The relationship between distance-to-camera and appearant-size is a very simple one: linear.

Camera twice as far, means the object will cover half as much of the viewport. The camera needs to be at a distance equal to the width of the grid multiplied by some constant value.

So why not simply set the camera at a distance MAX(C1*w, C2*h) from the front row of cylinders?

With w=grid width, h=grid-height, C1 and C2 are empirically determined constants.

Note: C2 will no longer be a fixed constant if you start varying the camera tilt. In that case, you will need a sin(tilt-angle) component in there.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.