1
votes

I am trying to make a 2D platform game using OpenGl and glut with C++. You can move your player around with the left and right arrow keys and jump with space. I have all the platforms loaded into the game through a text file and printed to the screen. This all works really good. The problem I am having is with the camera. When the right arrow key is pressed I have the players x position to increase. The problem is that when this happens I can not get the actual camera to move as well. This makes me think that instead of moving the player, I should use glTranslatef to translate all the platforms to the left. This seems a bit odd to me and I am just wondering if this is how it should be done. So I guess the final question is, should I translate the entire scene or move the player?

3

3 Answers

2
votes

Move the camera to follow the player by glTranslateing in the opposite direction as the player.

You should think of the camera like an in game object similar to the player and other movable items and the level as a static object with a fixed position. This makes placing in-game items and other things much easier.

2
votes

actually when you "move the camera" in OpenGL, since there is actually no camera, what is done internally, is exactly that, moving everything on the scene in the oposite direction.

As for the solution, if you're using glut, you can use

gluLookAt(x,  y,  z,
          ex, ey, ez,
          0,  1,  0)

where (x, y, z) is the coordinate where you want the camera to be, (ex, ey, ez) is the direction vector that you want the camera to look into (in reference to (x, y, z) coordinates) and (0, 1, 0) is the up vector. This function does all the matrix transformations necessary. More info here

If you're not using glut, but only raw OpenGL, the same link also explains the equivalent opengl calls you have to use to achieve exactly the same effect as gluLookAt

So when you want to move the camera (only right and left probably, since it's a platform game) you only have to change the x value

0
votes

I got this working using the following..

gl.PushMatrix()
gl.Translatef((1280/2)-float32((player.Body.Position().X)), 0, 0.0)

//Rest of drawing Code Code

gl.PopMatrix()

This is using OpenGL + Chipmunk Physics (in GoLang but should apply as these are just c-bindings). 1280 in this case is screen Width.