Answer the question
In order to leave comments, you need to log in
How to reduce C++ code size?
Hello. I use SDL 2.0 under C++. I want to implement keystrokes on the keyboard.
There is a processInput method which I call 60 times per second. But the problem is that I check each key, and it turns out to be cumbersome, how can I simplify it?
case SDL_KEYDOWN:
if (proccess_Event.key.keysym.sym == SDLK_A)
aIsDown = true;
if (proccess_Event.key.keysym.sym == SDLK_B)
bIsDown = true;
if (proccess_Event.key.keysym.sym == SDLK_C)
cIsDown = true;
if (proccess_Event.key.keysym.sym == SDLK_D)
dIsDown = true;
if (proccess_Event.key.keysym.sym == SDLK_E)
eIsDown = true;
if (proccess_Event.key.keysym.sym == SDLK_F)
fIsDown = true;
...
void Input::processInput()
{
SDL_PollEvent(&proccess_Event);
switch (proccess_Event.type)
{
case SDL_QUIT:
SDL_DestroyWindow(g_window);
SDL_Quit();
exit(0);
break;
case SDL_KEYDOWN:
if (proccess_Event.key.keysym.sym == SDLK_A)
aIsDown = true;
if (proccess_Event.key.keysym.sym == SDLK_B)
bIsDown = true;
if (proccess_Event.key.keysym.sym == SDLK_C)
cIsDown = true;
if (proccess_Event.key.keysym.sym == SDLK_D)
dIsDown = true;
if (proccess_Event.key.keysym.sym == SDLK_E)
eIsDown = true;
if (proccess_Event.key.keysym.sym == SDLK_F)
fIsDown = true;
...
}
}
inline bool isKeyDown(int keyNum)
{
return glfwGetKey(window, keyNum) == GLFW_PRESS;
}
Answer the question
In order to leave comments, you need to log in
Why can't you just take std::set or any other implementation of the Set data structure?
Pressed the button - added to set in O(1). They pressed the key - they removed it from the set in O (1). Need to check? Please - lookup O(1).
www.cplusplus.com/reference/set/set
Look at the switch construction, there will be less code.
In general, you can play around with map. Make a dictionary (key, the variable you need to make true).
And when pressed, look for map[key].
If you do not go into stl, then you can create 2 arrays, an array of keys and an array of positions. Look up the key in the array and then make bool at the same position true.
I'm not fluent in C++, but I would make it easier.
$aKeyCodes = [SDLK_A => 'user_name_func_for_A', SDLK_B => 'user_func_for_B', SDLK_C=> 'user_func_for_C']; //И так далее
if (array_key_exists($keyDownPress, $aKeyCodes) !== false) { // Вернет true если огонь
return $aKeyCodes[$keyDownPress]();
else
return false;
Do you really need a different click handler for each key? What problem are you solving?
If a handler for each key is not needed, then, as written above (you just need to check):
case SDL_KEYDOWN:
bool characterPressed = proccess_Event.key.keysym.sym >= SDLK_A && proccess_Event.key.keysym.sym <= SDLK_Z;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question