2d game camera implementation preserving aspect ratio with differents display size

Hi all,

this is my first post on this forum, i’m new to openGL but I’m trying to implement a 2d platform game on android using openGL.

First problem I’ve on android is that devices have different screen size and aspect ratio so my solution is to calculate stretched Width and Height preserving initial proportions.

this is my Camera object implementation (part of code is from an android book):



package com.badlogic.androidgames.framework.gl;

import javax.microedition.khronos.opengles.GL10;

import com.badlogic.androidgames.framework.impl.GLGraphics;
import com.badlogic.androidgames.framework.math.Vector2;

public class Camera2D {

	public final Vector2 position;
	public float zoom;
	public final float frustumWidth;
	public final float frustumHeight;
	final GLGraphics glGraphics;

	public Camera2D(GLGraphics glGraphics, float frustumWidth, float frustumHeight) {
		this.glGraphics = glGraphics;
		this.frustumWidth = frustumWidth;
		this.frustumHeight = frustumHeight;
		this.position = new Vector2(frustumWidth / 2, frustumHeight / 2);
		this.zoom = 1.0f;
	}

	public void setViewportAndMatrices() {

		GL10 gl = glGraphics.getGL();

		float displayWidth = (float) glGraphics.getWidth();
		float displayHeight = (float) glGraphics.getHeight();

		float calcWidthFloat = ((frustumHeight * displayWidth) / displayHeight);
		int calcWidth = (int) calcWidthFloat;

		gl.glViewport(0, 0, (int) displayWidth, (int) displayHeight);
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		gl.glOrthof(position.x - calcWidth * zoom / 2,
                	position.x + calcWidth * zoom / 2,
                	position.y - frustumHeight * zoom / 2,
                	position.y + frustumHeight * zoom / 2,
                	1, -1);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glLoadIdentity();
	}

	public void touchToWorld(Vector2 touch) {
		touch.x = (touch.x / (float) glGraphics.getWidth()) * frustumWidth * zoom;
		touch.y = (1 - touch.y / (float) glGraphics.getHeight()) * frustumHeight * zoom;
		touch.add(position).sub(frustumWidth * zoom / 2, frustumHeight * zoom / 2);
	}

}



I initialize Camera2D object with frustumWidth = 320 and frustumHeight = 480, and my game will be based on this dimentions.
Everithing scale mantaining proportion, but my result is not what i espect.

My problem is that on little devices everithing it’s ok, but on bigger devices images stretching is not accurate, proportions are preserved but final image is not accurate.
I define as accurate a streched image obtained trough an image manipulation program like “the gimp”;

so my question is:

there’s something wrong with my code???
maybe I must use bigger images for bigger devices???
is this problem caused by pixel density on the screen???

sorry for some English mistakes, I’m italian :frowning:

please help me find an easy solution :tired:

thx