I have worked on creating a gameloop and so far all of the code was inside a main.cpp file and I want to separate it into different files.
Which caused several problems:
My code is separated into 3 main functions in main(); which are input simulate and render.
I was able to separate the input code into its own file, however I ran into 2 problems I had to fix:
#include <iostream>
#include <SDL.h>
#include "input.h"
extern bool isMainLoopActive;
extern bool isMoveRightPressed;
extern bool isMoveLeftPressed;
extern bool isMoveUpPressed;
extern bool isMoveDownPressed;
struct detected_keys {
bool right = true;
bool left = true;
bool up = true;
bool down = true;
};
detected_keys movement_keys;
void input() {
// player control of box
const Uint8* currentKeyStates = SDL_GetKeyboardState(NULL);
if (currentKeyStates[SDL_SCANCODE_RIGHT]) {
isMoveRightPressed = true;
movement_keys.right = true;
}
if (currentKeyStates[SDL_SCANCODE_LEFT]) {
isMoveLeftPressed = true;
movement_keys.left = true;
}
if (currentKeyStates[SDL_SCANCODE_UP]) {
isMoveUpPressed = true;
movement_keys.up = true;
}
if (currentKeyStates[SDL_SCANCODE_DOWN]) {
isMoveDownPressed = true;
movement_keys.down = true;
}
return;
}
The 2 problems are:
- While I was coding in one large main.cpp file I was able to have a lot of functions and variables at the top of the file which were all global. Now that I moved the input() to a new file I lost direct access to the global variables.
So what I did first was use
extern bool isMainLoopActive;
extern bool isMoveRightPressed;
extern bool isMoveLeftPressed;
extern bool isMoveUpPressed;
extern bool isMoveDownPressed;
to simply get access to these variables back. However I read somewhere that one should avoid relying on global variables.
So I looked for a way to transfer the 4 key presses represented as boolean variables from one function to another as a struct.
However if I want to use a struct of the type "detected_keys" then I would have also declare that type in the other files, which would be the same as just using extern variables all over.
So what is the best approach here if global variables are supposedly to not be used?
Is all code in videogames basically functions passing values over to each other in large packages? And if so, is there a data type that is better for that than struct?