[How To] Mouse Position relative to View

[How To] Mouse Position relative to View
0.0 0


I did read some threads about how to get Cursor Pos in cocos2dx, etc…

This should only work on Windows

Now heres some code for you:

void GetWindowPos(HWND hWnd, int *x, int *y)
    HWND hWndParent = GetParent(hWnd);
    POINT p = {0};

    MapWindowPoints(hWnd, hWndParent, &p, 1);

    (*x) = p.x;
    (*y) = p.y;

Needed to get exact view position (the black box)
And NOT the hole windows, with bar etc.

In your Update, or where you wanna have the position do this:

POINT point;
    int x = point.x;
    int y = point.y;

    int positionX;
    int positionY;
    GetWindowPos(CCEGLView::sharedOpenGLView()->getHWnd(), &positionX, &positionY);
    x-= positionX;
    y-= positionY;

    CCLog("Mouse Pos: %i %i", x, y);
    CCLog("Something wrong");

You can also save it in an CCPoint if you need,

CCPoint cursorPos = ccp(x,y);

Just add this somewhere after “y~~= positionY;”
Have fun, and you can easily make an “MouseMove” Event with that.
Care, this is the position from origin TOP-LEFT
NOT Bottom-Left **
Bottom-Left Addition:
y~~= CCDirector::sharedDirector()->getWinSize().height;

Care: This gives you negative values when going up. 0/0 bottom\_left

You may add this to cocos2dx wiki if you wan’t

Mouse cursor position without clicking

In version 3.0 you can use following function i wrote:

cocos2d::Point get_cursor_pos()
    EGLView* egl_view = Director::getInstance()->getOpenGLView();
    GLFWwindow* window = egl_view->getWindow();
    double px, py;
    glfwGetCursorPos(window, &px, &py);

    //TODO: cache window size
    int x,y;
    glfwGetWindowSize(window, &x, &y);

    return cocos2d::Point(px, y-py);

It is platform independent, as it uses glfw, and i also did coordinate transformation from left-top to the left-bottom, because cocos objects use the latter.


This gives error. What do i have to include . Thanks


This gives a error. No such thing as sharedOpenGLView it says for that class


you dont need to do this in the latest cocos2d-x … since onMouseMove is provided :slight_smile:


void Control6::onMouseMove(cocos2d::EventMouse *event)

_cursorPosition = Vec2(event->getCursorX(),event->getCursorY());



Yes, but On Mouse Move we have to be clicked down. I need track windows mouse without any clicking. This of course then is only a Windows feature of course. i suppose maybe best design my mechanism with Mouse Down as this is what all handheld devices offer only


on mouse move it doesnt have to be clicked down



When someone wants to position nodes depending on cursor pos, for example, in init() funtion, detecting cursor pos in onMouseMove() is not the solution. :face_with_raised_eyebrow:


double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);

to get the position