Code: Select all
//Make this its own header file
//You don't need to initalize any of the variables for the camera, everything is ready to go, but if you want to make your game world bigger or smaller you can change WORLDWIDTH && WORLDHEIGHT
//Include the file in Game.h: #include "Camera.h"
//Implement in Game.h like this: Camera camera, and call camera.Update(Vei2 playerPos, int playerWidth, int playerHeight); in game.cpp in UpdateModel().
//Uses a Vei2 for camera and player position.
//Make sure to subtract camera.pos.x && camera.pos.y for anything that would need to scroll especially the player.
//Example: gfx.DrawPlayer(x - camera.pos.x, y - camera.pos.y, color); this wont affect the position at which you initially draw your player
//Anything that scrolls off screen will have to use some form of clipping.
//Here is a function for PutPixelClipping
/*void Graphics::PutPixelClipped(int x, int y, Color c)
{
if (x < Graphics::ScreenWidth && x >= 0 && y < Graphics::ScreenHeight && y >= 0)
pSysBuffer[x + Graphics::ScreenWidth * y] = c;
}*\
//Works just like the standard PutPixel except for the clipping aspect. Any function that uses PutPixel can be swapped to PutPixelClipped to allow it scroll off screen
#pragma once
#include "Vei2.h"
class Camera
{
private:
static constexpr int CTRKOFFVERT = 50;
static constexpr int CTRKOFFHOR = 240;
static constexpr int WORLDWIDTH = 2000;
static constexpr int WORLDHEIGHT = 1199;
public:
Vei2 pos;
void Update(Vei2 playerPos, int playerWidth, int playerHeight)
{
// convert player world coordinates to screen coordinates
int px = playerPos.x - pos.x;
int py = playerPos.y - pos.y;
int width = playerWidth;
int height = playerHeight;
int ScreenWidth = 800;
int ScreenHeight = 600;
// scroll camera if player is out of tracking rectangle
if (px < CTRKOFFHOR)
{
pos.x = playerPos.x - CTRKOFFHOR;
}
if (px + width > ScreenWidth - CTRKOFFHOR)
{
pos.x = playerPos.x + width + CTRKOFFHOR - ScreenWidth;
}
if (py < CTRKOFFVERT)
{
pos.y = playerPos.y - CTRKOFFVERT;
}
if (py + height > ScreenHeight - CTRKOFFVERT)
{
pos.y = playerPos.y + height + CTRKOFFVERT - ScreenHeight;
}
// clamp camera so that the screen does not exceed
// the edge of the world
if (pos.x < 0)
{
pos.x = 0;
}
else if (pos.x + ScreenWidth > WORLDWIDTH)
{
pos.x = WORLDWIDTH - ScreenWidth;
}
if (pos.y < 0)
{
pos.y = 0;
}
else if (pos.y + ScreenHeight > WORLDHEIGHT)
{
pos.y = WORLDHEIGHT - ScreenHeight;
}
}
};