This has been bugging me for ages but I finally worked it out.
Cameras in OpenGL (C++)
So you have a 3D scene drawn out with some nice cubes and cylinders - and it looks pretty nice! But you don't know how to control the camera.
In OpenGL there is no camera - and there doesn't need to be.
Take the Futurama principle: the ship doesn't move; it merely moves the rest of the Universe in the opposite direction.
With this in mind, we simply need to add a rotation to the beginning of the draw() function, like so:
Two variables: rotateX and rotateY.
rotateX is our rotation around the X axis - imagine you are folding a piece of paper towards you. rotateY is our rotation around the Y axis, like turning a mug of coffee in place.
We just need to assign this to keys! I'm using the arrow keys.
NB: better to replace 10 with a preset constant so you can change it later.
Now that we know this, it's simple to move the camera in any way we want. To move forwards and backwards, we just have to do the same but with a translation instead of a rotation. So in our draw() function we add:
Cameras in OpenGL (C++)
So you have a 3D scene drawn out with some nice cubes and cylinders - and it looks pretty nice! But you don't know how to control the camera.
In OpenGL there is no camera - and there doesn't need to be.
Take the Futurama principle: the ship doesn't move; it merely moves the rest of the Universe in the opposite direction.
With this in mind, we simply need to add a rotation to the beginning of the draw() function, like so:
glRotatef(rotateX, 1, 0, 0);
glRotatef(rotateY, 0, 1, 0);
Two variables: rotateX and rotateY.
rotateX is our rotation around the X axis - imagine you are folding a piece of paper towards you. rotateY is our rotation around the Y axis, like turning a mug of coffee in place.
We just need to assign this to keys! I'm using the arrow keys.
if (Event.Type == sf::Event::KeyPressed)
{
switch (Event.Key.Code)
{
case sf::Key::Left:
rotateY -= 10;
break;
case sf::Key::Right:
rotateY += 10;
break;
case sf::Key::Up:
rotateX -= 10;
break;
case sf::Key::Down:
rotateX += 10;
break;
}
}
NB: better to replace 10 with a preset constant so you can change it later.
Now that we know this, it's simple to move the camera in any way we want. To move forwards and backwards, we just have to do the same but with a translation instead of a rotation. So in our draw() function we add:
glTranslatef(x, y, z);