How to Create a Camera in SDL2

Hello everyone, how do I make a camera that follows my player in SDL without the use of OpenGL? I searched up and watched some tutorials but the code never worked for me. A step-by-step code with some explanation would be of big help.

Thanks in advance!

I don’t know about 3D, but in a 2D game (side-scrolling, top-town, or whatever) I would design my drawing code so that it only draws part of the world depending on some x, y, width, height and possibly other attributes such as zoom-level.

Ignoring the zoom, the width and height could essentially be the size of the window, and x and y could be the position of the player. If x and y refers to the top-left corner rather than the center then you might want to calculate x as…

x = player.x + player.width / 2 - width / 2

…and similar for y.

This would keep the player centered at all times. If this is not what you want you would have to adjust it a little.

Maybe you don’t want to move the “camera” when the player is moving around in the middle part of the screen, and instead only move the the “camera” when the player moves too far to the left or too far to the right to ensure that at least one quarter (25%) of the screen is always visible on both sides of the player…

if (player.x < x + width / 4)
{
	x = player.x + player.width / 2 - width / 4;
}
else if (player.x > x + 3 * width / 4)
{
	x = player.x + player.width / 2 - 3 * width / 4;
}
else
{
	leave x unmodified
}

If you want to make the camera move smoother you would have to make further adjustments but I think the above is a good start.

Note that the code I have posted is just pseudocode and have not been tested. It’s just to demonstrate what I’m talking about. You’ll still need to think through and understand the math to make sure it works correctly the way you want it.

sorry to necro this thread but I found the following article on Mozilla’s web docs on implementing tilemaps and camera for JS and Canvas[0]. If you follow this and study the source code[1] it shouldn’t be difficult to rewrite in C or C++.

[0]Square tilemaps implementation: Scrolling maps - Game development | MDN

[1]GitHub - mozdevs/gamedev-js-tiles: Examples of tile maps implementation with the Canvas API