Maybe that's my lack of c++ knowledge or lack of programing skills, but i'm trying to understand command design pattern in c++ for game development. I'm reading this book (its literally called "Game Programing Patterns" and i quite like it), and i decided to use one of the design patterns in real code to see if i really get it. So i created this scrap code, which unsurprisingly doesnt work:
#include <iostream>
void jump() {
//assume that this is some random
//code that makes player jump
//if console displays "Player jumps"
//this means that this code works...
std::cout << "Player jumps";
}
void fireGun() {
//same thing as jump function
//but its for fire gun
std::cout << "Gun goes pew pew";
}
class Command
{
public:
virtual ~Command(){}
virtual void execute() = 0;
};
class JumpCommand : public Command
{
public:
virtual void execute() { jump(); }
};
class FireCommand : public Command
{
public:
virtual void execute() { fireGun(); }
};
class InputHandler
{
public:
void handleInput();
/// Methods to bind commands????
private:
Command* buttonX_;
Command* buttonY_;
};
void InputHandler::handleInput() {
bool is_BUTTON_A_pressed = true;
//lets assume that this is a function that detects
//if button a ir pressed and it returns true
//(meaning button a is pressed)
if (is_BUTTON_A_pressed) buttonX_->execute();
}
int main()
{
InputHandler input;
input.handleInput();
return 0;
}
for those wondering here is the source from where i pulled out this design pattern example code: https://gameprogrammingpatterns.com/command.html
So the thing that confuses me the most is "Methods to bind commands" part (which i commented in code), i have a feeling like it has something to do with binding buttonX_ and buttonY_ to command, but thats it...
What your missing is binding buttonX_ and buttonY_ to do something. I think all you're missing is a constructor (or some other mechanism) that does something like this:
buttonX_ = new JumpCommand();
buttonY_ = new FireCommand();
Right now, they're not pointing to anything. Point them to something and you'll be happier.