I just converted the tutorial code to do what I was trying to explain in my previous post:
#include <iostream>
#include <boost/function.hpp>
#include <SFML/Graphics.hpp>
enum InputType
{
KeyboardInput,
MouseInput,
JoystickInput
};
struct MyKeys
{
InputType myInputType;
sf::Event::EventType myEventType;
sf::Key::Code myKeyCode;
sf::Mouse::Button myMouseButton;
};
static bool operator<(const MyKeys& a, const MyKeys& b)
{
if(a.myInputType != b.myInputType)
return a.myInputType < b.myInputType;
else if(a.myEventType != b.myEventType)
return a.myEventType < b.myEventType;
else if(KeyboardInput == a.myInputType)
return a.myKeyCode < b.myKeyCode;
else if(MouseInput == a.myInputType)
return a.myMouseButton < b.myMouseButton;
else
return false;
}
bool TestEvent (MyKeys k, sf::Event e);
void Shoot (void);
void Jump(void);
void Use(void);
int main(int argc, char** argv)
{
//Variables for main
sf::RenderWindow App;
bool Running = true;
sf::Event Event;
//Variables for demo
typedef std::map<MyKeys,boost::function<void (void)> > BindingMap;
typedef BindingMap::iterator BindingIterator;
BindingMap Keys;
MyKeys key;
//Let's bind the left mouse button to the "Shoot" action
key.myInputType = MouseInput;
key.myEventType = sf::Event::MouseButtonPressed;
key.myMouseButton = sf::Mouse::Left;
Keys[key] = &Shoot;
//Let's bind the Return key to the "Jump" action
key.myInputType = KeyboardInput;
key.myEventType = sf::Event::KeyPressed;
key.myKeyCode = sf::Key::Return;
Keys[key] = &Jump;
//Let's bind the Left Control key to the "Use" action
key.myInputType = KeyboardInput;
key.myEventType = sf::Event::KeyPressed;
key.myKeyCode = sf::Key::LControl;
Keys[key] = &Use;
//Window creation
App.Create(sf::VideoMode(640, 480, 16), "config test");
//Main loop
while (Running)
{
//Manage Events
while (App.GetEvent(Event))
{
//Using Event normally
//Window closed
if (Event.Type == sf::Event::Closed)
{
Running = false;
}
//Key pressed
else if (Event.Type == sf::Event::KeyPressed && sf::Key::Escape == Event.Key.Code)
{
Running = false;
}
else if (Event.Type == sf::Event::KeyPressed && sf::Key::A == Event.Key.Code)
{
std::cout<<"Key A !"<<std::endl;
}
//Using Event for binding
else
{
key.myEventType = Event.Type;
switch(Event.Type)
{
case sf::Event::KeyPressed:
case sf::Event::KeyReleased:
key.myInputType = KeyboardInput;
key.myKeyCode = Event.Key.Code;
break;
case sf::Event::MouseButtonPressed:
case sf::Event::MouseButtonReleased:
key.myInputType = MouseInput;
key.myMouseButton = Event.MouseButton.Button;
break;
default:
continue; // skip to next event
}
BindingIterator it = Keys.find(key);
// Binding for event found - execute bound action
if(Keys.end() != it)
it->second();
}
}
//Display the result
App.Display();
}
//End of application
return EXIT_SUCCESS;
}
void Shoot (void)
{
std::cout<<"Shoot !"<<std::endl;
}
void Jump (void)
{
std::cout<<"Jump !"<<std::endl;
}
void Use (void)
{
std::cout<<"Use !"<<std::endl;
}