so i am creating a game similar to super-smash-bros, in which the camera should zoom in on players when they are close together, and scale back when they are apart. I create a window for my game via

m_pWindow = SDL_CreateWindow("First SDL game attempt", SDL_WINDOWPOS_UNDEFINED,
                SDL_WINDOWPOS_UNDEFINED, 1000, 1000, SDL_WINDOW_SHOWN);

and then initialise my render via

m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, SDL_RENDERER_ACCELERATED); 

and when i call render for my buffer, it simply calls

SDL_SetRenderDrawColor(m_pRenderer, m_clearRed, m_clearGreen, m_clearBlue, 0xff);

Now i am wondering where in this solution should i implement the camera, if you could point me in the right direction that would be great. For example, i have a player positioned at {500, 800}, and another at {300,800}. I want to zoom in on this point of the screen. The total window is 1000x1000, but rendering {x = 200->600, y = 600->1000} is what i want to achieve.

I have currently tried using

SDL_Rect rect;
rect.x = 0;
rect.y = 0;
rect.w = 900; //TEST VALUES
rect.h = 900; //TEST VALUES

But this simply doesn't render part of the screen, as opposed to scaling the entire view.

Any other help would be greatly appreciated


As it seems there is no thing like a camera in SDL you have to implement that by yourself. The call you found SDL_RenderSetViewport(...) is indeed for a very different purpose, it adjusts the size (and offset) of the area within your window to draw to. That is useful e.g. if the window is resized.

Where to implement the camera is rather simple, you just need to calculate the bounding box of the locations of your players and take its center and size for your rendering. This center (translation) and size (scale) are what defines a camera in 2D (actually there could be also rotation but that's it).

How to apply is rather difficult, since (AFAIK) there is no pendant in SDL for it. You have to do it explicitly on your one. You should never change the actual position of your players, instead you have to calculate a on screen position for every render cycle (frame). One example for this can be found here.

If you want to do this more efficiently on the GPU, you could use OpenGL see here (Notice this is about legacy OpenGL). You could also use modern (core profile) OpenGL, but I think that this is rather a bit too hard for a simple 2D game.

  • \$\begingroup\$ I am using Box2D for my world, does this present any further problems? \$\endgroup\$ – Ryan Turnbull Oct 24 '17 at 2:20
  • \$\begingroup\$ @RyanTurnbull No, I don't see there any problem for this, especially because you have to implement the calculation yourself. It doesn't matter where you get your locations from for the rendering. \$\endgroup\$ – Cryptjar Oct 24 '17 at 2:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.