2D_game_Command - 8BitsCoding/RobotMentor GitHub Wiki
Command Pattern
๋ช ๋ น์์ฒด๋ฅผ ์ค๋ธ์ ํธ๋ก ๋ง๋ค์ด๋ณด์.
ํค๋ณด๋ ์ ๋ ฅ์ ๋ฐ๋ฅธ ์ฒ๋ฆฌ๋ฅผ ๋ง๋๋ คํ๋ค.
void update() override
{
// move tank
if (isKeyPressed(GLFW_KEY_LEFT)) tank.center.x -= 0.5f * getTimeStep();
if (isKeyPressed(GLFW_KEY_RIGHT)) tank.center.x += 0.5f * getTimeStep();
if (isKeyPressed(GLFW_KEY_UP)) tank.center.y += 0.5f * getTimeStep();
if (isKeyPressed(GLFW_KEY_DOWN)) tank.center.y -= 0.5f * getTimeStep();
// rendering
tank.draw();
}
์.. ์์ฒญ๋๋ฐ... ๊ฐ์ฒด๊ฐ tankํ๋๋ฟ์ด๊ณ ํค๋ณด๋๋ฅผ ๋ฐฉํฅํค๋ง ๋ฐ์๋ ์ ์ ๋๋ฐ...
๋ช ๋ น์ ์ฒ๋ฆฌํ๋ ๊ฐ์ฒด๋ฅผ ๋ง๋ค์ด๋ณด์.
void update() override
{
input_handler.handleInput(*this, tank, getTimeStep());
// rendering
tank.draw();
}
class InputHandler
{
public:
Command * button_up = nullptr;
//std::map<int, Command *> key_command_map;
InputHandler()
{
button_up = new UpCommand;
}
void handleInput(Game2D & game, Actor & actor, float dt)
{
if (game.isKeyPressed(GLFW_KEY_UP)) button_up->execute(actor, dt);
/*for (auto & m : key_command_map)
{
if (game.isKeyPressed(m.first)) m.second->execute(actor, dt);
}*/
}
};
class Command
{
public:
virtual ~Command() {}
virtual void execute(Actor& actor, float dt) = 0;
};
class UpCommand : public Command
{
public:
virtual void execute(Actor& actor, float dt) override
{
actor.moveUp(dt);
}
};
class Actor
{
public:
virtual void moveUp(float dt) = 0;
};
class MyTank : public Actor
{
public:
vec2 center = vec2(0.0f, 0.0f);
//vec2 direction = vec2(1.0f, 0.0f, 0.0f);
void moveUp(float dt) override
{
center.y += 0.5f * dt;
}
void draw()
{
beginTransformation();
{
translate(center);
drawFilledBox(Colors::green, 0.25f, 0.1f); // body
translate(-0.02f, 0.1f);
drawFilledBox(Colors::blue, 0.15f, 0.09f); // turret
translate(0.15f, 0.0f);
drawFilledBox(Colors::red, 0.15f, 0.03f); // barrel
}
endTransformation();
}
};