Home > Articles > Home & Office Computing > Entertainment/Gaming/Gadgets

  • Print
  • + Share This
Like this article? We recommend

Setting the Aspect Ratio

You have to set the aspect ratio so that the objects are rendered correctly. This part of the code (see Listing 3) is untouched, so it is basically the same as in Sun's example. First, the width and length of the canvas are checked; then the aspect ratio is calculated according to the type of Camera.

Listing 3. Setting the aspect ratio

void setupAspectRatio() {
 viewport_x = 0;
 viewport_y = 0;
 viewport_width = myCanvas.getWidth();
 viewport_height = myCanvas.getHeight();
 Camera cam = myWorld.getActiveCamera();
 float[] params = new float[4];
 int type = cam.getProjection(params);
 if(type != Camera.GENERIC) {
  //calculate window aspect ratio
  float waspect=viewport_width/viewport_height;
  if (waspect<params[1]) {
   float height = viewport_width/params[1];
   viewport_height=(int)height;
   viewport_y=(myCanvas.getHeight()-viewport_height)/2;
  }
  else {
   float width = viewport_height*params[1];
   viewport_width=(int)width;
   viewport_x=(myCanvas.getWidth()-viewport_width)/2;
  }
 }
}
  • + Share This
  • 🔖 Save To Your Account