I’ve started to try and handle events but I get some strange behavior.
I cam across two sets of working ways to handle events, one on the
programmers guide and the other on games from scratch.
EventListenerMouse *me = EventListenerMouse::create();
me->onMouseDown = CC_CALLBACK_1(HelloWorld::onMouseDown, this);
me->onMouseUp = CC_CALLBACK_1(HelloWorld::onMouseUp, this);
me->onMouseUp = CC_CALLBACK_1(HelloWorld::onMouseMove, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(me,this);
void HelloWorld::onMouseDown(cocos2d::Event *ev) {
EventMouse* e = (EventMouse*)ev;
CCLOG("mouse down %f, %f",e->getLocation().x,e->getLocation().y);
}
void HelloWorld::onMouseMove(cocos2d::Event *ev) {
EventMouse* e = (EventMouse*)ev;
CCLOG("mouse move %f, %f",e->getCursorX(),e->getCursorY());
}
void HelloWorld::onMouseUp(cocos2d::Event *ev) {
EventMouse* e = (EventMouse*)ev;
CCLOG("mouse up %f, %f",e->getLocation().x,e->getLocation().y);
}
auto listener = EventListenerMouse::create();
listener->onMouseDown = [](cocos2d::Event* event){
try {
EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
mouseEvent->getMouseButton();
std::stringstream message;
message << "Mouse event: Button: " << mouseEvent->getMouseButton() << "pressed at point (" <<
mouseEvent->getLocation().x << "," << mouseEvent->getLocation().y << ")";
MessageBox(message.str().c_str(), "Mouse Event Details");
}
catch (std::bad_cast& e){
// Not sure what kind of event you passed us cocos, but it was the wrong one
return;
}
};
listener->onMouseMove = [](cocos2d::Event* event){
// Cast Event to EventMouse for position details like above
cocos2d::log("Mouse moved event");
};
listener->onMouseScroll = [](cocos2d::Event* event){
cocos2d::log("Mouse wheel scrolled");
};
listener->onMouseUp = [](cocos2d::Event* event){
cocos2d::log("Mouse button released");
};
_eventDispatcher->addEventListenerWithFixedPriority(listener, 1);
The way described in the programmers manual seems to only call onmousemove once, while the way described in the excerpt from games from scratch gets called every frame.
Is there a way to make the code from the programmers manual fire every frame?
What’s the best practice way to handle events now?