Reza Ghobadinic

Mouse

Handling mouse events are quite strait forward. Lets jump to the code and I’ll explain. I assume you have read the previous posts.

The header file doesn’t have anything special! Just our standard Scene/Layer header…

#ifndef MouseScene_h
#define MouseScene_h

#include "cocos2d.h"

USING_NS_CC;

class MouseScene : public Layer
{
public:
    static Scene* createScene();
    virtual bool init();
    CREATE_FUNC(MouseScene);
};

#endif /* MouseScene_h */

Here in the cpp file, we use EventListenerMouse to create a mouse listener and add it to the dispatcher.

There are four events in the mouse event listener:

I set them up using C++ Lambdas this time, instead of member methods, to save some code space. But, in the source that you can download, I have included the member methods too!

Notice that we have to cast the Event to MouseEvent to be able to access the mouse event methods. The methods include:

#include "MouseScene.h"
#include 

USING_NS_CC;
using namespace std;

Scene* MouseScene::createScene()
{
    auto scene = Scene::create();
    auto layer = MouseScene::create();

    scene->addChild(layer);
    
    return scene;
}

bool MouseScene::init()
{
    auto listener = EventListenerMouse::create(); // Create a mouse listener
    
    listener->onMouseUp = [] (Event* event){
        EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
        cout << "Button Up: " << (int)mouseEvent->getMouseButton() << endl; 
    };

    listener->onMouseDown = [] (Event* event){
        EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
        cout << "Button Down: " << (int)mouseEvent->getMouseButton() << endl; 
    };

    listener->onMouseMove = [] (Event* event){
        EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
        cout << "X: " << mouseEvent->getCursorX() << endl;
        cout << "Y: " << mouseEvent->getCursorY() << endl; 
    };

    listener->onMouseScroll = [] (Event* event){
        EventMouse* mouseEvent = dynamic_cast<EventMouse*>(event);
        cout << "Scroll X = " << mouseEvent->getScrollX() << endl;
        cout << "Scroll Y = " << mouseEvent->getScrollY() << endl; 
    };

    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
    
    return true;
}

If you run this code, it will print all sorts of information in the output.

Mouse buttons are 0, 1, 2, 3, 4, etc…

If you move the mouse, it will print the position of the cursor relative to the cocos screen.

If you turn the scroll, it will print the Y amount of the scroll.

Download Source

Exit mobile version