Question

I'm beginner in making games in OpenGL. I drew a map (this is world, there player can move) and now I want to do, that camera follows the player (player is in center of the screen). I've done something like this:

GLU.gluLookAt(gl, 
                this.x, this.y, 0,
                this.x, this.y, 1.0f,
                0.0f, 0.0f, 0.0f);

Where this.x and this.y are coordinates of player. Unfortunately It doesn't work :( Nothing happens. This is 2d game so there aren't any perpective etc.

Was it helpful?

Solution

You could do this a few ways but the easiest is probably just to call

gl.glTranslatef( cameraX, cameraY );

After your glLoadIdentity call but before rendering your frame.

glTranslatef has a cumulative effect so everything in your scene will be drawn offset by cameraX and cameraY.

One catch is that for this to work you need to be making use of glPushMatrix and glPopMatrix instead of calling glLoadIdentity before rendering each object otherwise you would loose the camera translation.


Just a side note, if you planning on having a huge world you should make the player's position 0,0 and make your world move instead of your player. Not a big issue if it's a small game but when objects have really large x and y values then you can run into problems with floating point rounding errors. It might not be something you ever run into but it's nice to know I guess.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top