I’ve been trying to add a viewport to my game using SDL2, however it just won’t work.
What I want my viewport to do is to always follow the player, and how I do this is by assigning the players x and y to my viewport rect’s x and y.
But, it doesn’t work out as I expected it to, instead the viewport always “falls behind” or the player is faster than the viewport.
Here’s a GIF on what my problem is :
As you can see, the viewport doesn’t follow the player like it should.
This is my Camera class, where the viewport is initialized, drawn and so on :
Camera::Camera(Uint16 x, Uint16 y, Uint16 w, Uint16 h)
{
// Sets up the viewport positions and sizes
viewport.x = x;
viewport.y = y;
viewport.w = w;
viewport.h = h;
// Sets the viewport so that SDL uses it
SDL_RenderSetViewport(Window::GetRenderer(), &viewport);
}
void Camera::DrawCameraViewport()
{
SDL_RenderSetViewport(Window::GetRenderer(), &viewport);
}
void Camera::SetCameraPosition(int _x, int _y)
{
viewport.x = _x;
viewport.y = _y;
}
Those two three are the most important ones.
Now, here’s how I call all of these functions in my Game class :
camera = new Camera(100, 100, 1024, 720);
camera->DrawCameraViewport();
camera->SetCameraPosition(SpriteManager::GetSprite("sprite1")->GetPosition().x, SpriteManager::GetSprite("sprite1")->GetPosition().y);
If you need more code, just tell me.
Thanks.