Use game coordinates for view and player positions

This commit is contained in:
Camden Dixie O'Brien 2024-12-28 12:34:09 +00:00
parent fad49a7d15
commit 6ca053f126

View File

@ -15,8 +15,8 @@
#define SCALE 4
#define TILESIZE 32
#define VIEWWIDTH 8
#define VIEWHEIGHT 6
#define VIEWWIDTH (8 * TILESIZE)
#define VIEWHEIGHT (6 * TILESIZE)
#define MAX_PATH_LEN 128
@ -71,7 +71,7 @@ int main(int argc, char *argv[])
assert(0 == err);
window = SDL_CreateWindow(
"2D Game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
SCALE * TILESIZE * VIEWWIDTH, SCALE * TILESIZE * VIEWHEIGHT, 0);
SCALE * VIEWWIDTH, SCALE * VIEWHEIGHT, 0);
assert(NULL != window);
renderer = SDL_CreateRenderer(window, -1, 0);
assert(NULL != renderer);
@ -161,10 +161,11 @@ int main(int argc, char *argv[])
pitex = IMG_LoadTexture(renderer, path);
assert(NULL != pitex);
int offx = 16, offy = 0;
// Initialize view and player
dvec_t vpos = { 512, 0 };
SDL_Rect psrc = { .y = 0, .w = PIWIDTH, .h = PIHEIGHT };
SDL_Rect pdest = { .w = SCALE * PIWIDTH, .h = SCALE * PIHEIGHT };
dvec_t pvel = { 0, 0 }, ppos = { 80, 80 };
dvec_t pvel = { 0, 0 }, ppos = { 640, 96 };
SDL_Event event;
uint64_t prevt = SDL_GetTicks64();
@ -236,10 +237,15 @@ int main(int argc, char *argv[])
SDL_RenderClear(renderer);
// Draw map
for (int y = 0; y < VIEWHEIGHT; ++y) {
for (int x = 0; x < VIEWWIDTH; ++x) {
const unsigned tileid
= map[x + offx + MAPSHIFTX][y + offy + MAPSHIFTY];
const int startx = TILESIZE * floor(vpos.x / TILESIZE);
const int starty = TILESIZE * floor(vpos.y / TILESIZE);
for (int y = starty; y < vpos.y + VIEWHEIGHT; y += TILESIZE) {
for (int x = startx; x < vpos.x + VIEWWIDTH; x += TILESIZE) {
const unsigned row = x / TILESIZE + MAPSHIFTX;
const unsigned col = y / TILESIZE + MAPSHIFTY;
if (row >= MAPWIDTH || col >= MAPHEIGHT)
continue;
const unsigned tileid = map[row][col];
if (0 == tileid)
continue;
const SDL_Rect src = {
@ -249,8 +255,8 @@ int main(int argc, char *argv[])
.h = TILESIZE,
};
const SDL_Rect dest = {
.x = SCALE * TILESIZE * x,
.y = SCALE * TILESIZE * y,
.x = SCALE * (x - vpos.x),
.y = SCALE * (y - vpos.y),
.w = SCALE * TILESIZE,
.h = SCALE * TILESIZE,
};
@ -261,8 +267,8 @@ int main(int argc, char *argv[])
// Draw player
const unsigned piframe = (t / BASEANIMPERIOD) % PIANIMLEN;
psrc.x = PIWIDTH * piframe;
pdest.x = SCALE * (int)ppos.x;
pdest.y = SCALE * (int)ppos.y;
pdest.x = SCALE * (int)(ppos.x - vpos.x);
pdest.y = SCALE * (int)(ppos.y - vpos.y);
SDL_RenderCopy(renderer, pitex, &psrc, &pdest);
SDL_RenderPresent(renderer);