Problem With Viewport Camera[SDL2]

I made piece of code to give my game a camera, SDL_RenderSetViewport(rend, &cam); I used a viewport as a camera and made a rect as the position and dimensions for it. But everytime I move it to the left cam.x -= 2; and it gets to end of the left side of the window everything I have rendered disappears, but when I move it to the right cam.x += 2; it moves to the left. I changed the starting x so it wouldn’t start at 0, it fixed the inverted direction but when it reaches the left side everything still goes invisible.

I have only been using SDL 2 for 3 months now, so if anyone has any tips what’s happening to the renderer, please post it.
Thanks :smiley:

That’s not really how the viewport is supposed to be used. The viewport is used to “set the drawing area for rendering on the current target” (

What you want to do instead is offset your objects (player, enemies and such) by the camera position to make the illusion that the objects are moving to the left whenever the camera is moving to the right. Example code below:

#include "SDL.h"

#define WINDOW_WIDTH	800
#define WINDOW_HEIGHT	600
#define PLAYER_WIDTH	32
#define PLAYER_HEIGHT	32

float PlayerPosX = (WINDOW_WIDTH / 2)  - (PLAYER_WIDTH / 2);
float PlayerPosY = (WINDOW_HEIGHT / 2) - (PLAYER_HEIGHT / 2);

float CameraPosX = 0.0f;
float CameraPosY = 0.0f;

float SpeedX = 10.0f;
float SpeedY = 10.0f;

bool Running = true;

SDL_Rect PlayerRect = {(int)PlayerPosX, (int)PlayerPosY, PLAYER_WIDTH, PLAYER_HEIGHT};

SDL_Event Event;

int main(int argc, char* argv[])
	// Initialize SDL and such

			case SDL_QUIT:
					Running = false;


			case SDL_KEYDOWN:
					// Move the camera

					if(Event.key.keysym.sym == SDL_SCANCODE_UP)
						CameraPosY -= SpeedY;

					else if(Event.key.keysym.sym == SDL_SCANCODE_DOWN)
						CameraPosY += SpeedY;

					if(Event.key.keysym.sym == SDL_SCANCODE_LEFT)
						CameraPosX -= SpeedX;

					else if(Event.key.keysym.sym == SDL_SCANCODE_RIGHT)
						CameraPosX += SpeedX;


		// Offset the player quad by the camera position
		PlayerRect.x = (int)(PlayerPosX - CameraPosX);
		PlayerRect.y = (int)(PlayerPosY - CameraPosY);

	// Quit SDL and such

	return 0;

Let me know if you have any more questions :slight_smile:


Here you can learn more about the usage of the viewport:
And learn more about camera scrolling:

Ohhhh :open_mouth:
When you think you of it like that you don’t really need a Viewport, and thanks also for the tutorial on cameras! :smiley: