cocos2d-x
cocos2d-x copied to clipboard
Bug: EventMouse getLocation return location in screen coordinates, not in OpenGL coordinates
- cocos2d-x version: since version 4.0
- devices test on: Mac OS 11.2.1
- developing environments
- NDK version:
- Xcode version:
- VS version:
- browser type and version:
Steps to Reproduce:
Just add a EventListenerMouse to Scene, and get the location of mouse down. In the C++ API document, the returned location is in OpenGL coordinates, but it's in screen coordinates actually.
This is my code.
bool GameScene::init() {
if ( !Scene::init() )
{
return false;
}
auto listener = EventListenerMouse::create();
listener->onMouseDown = CC_CALLBACK_1(GameScene::onMouseDown, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
void GameScene::onMouseDown(Event *event) {
auto *e = dynamic_cast<EventMouse *>(event);
switch (e->getMouseButton()) {
case EventMouse::MouseButton::BUTTON_LEFT: {
auto p = e->getLocation();
printf("%f %f\n", p.x, p.y);
break;
}
default:
break;
}
}
I had checked the code in CCGLViewImpl-mac.mm/CCGLViewImpl-desktop.cpp and CCEventMouse.cpp and find the reason
In the callback function void GLViewImpl::onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y), the x and y is set to the value in screen coordinates, relative to the upper-left corner of the client area of the window. The glfw document is here https://www.glfw.org/docs/3.1/group__input.html#ga7dad39486f2c7591af7fb25134a2501d
So the _mouseX and _mouseY is in screen coordinates
in function onGLFWMouseMoveCallBack (CCGLViewImpl-mac.mm/CCGLViewImpl-desktop.cpp)
//Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here
float cursorX = (_mouseX - _viewPortRect.origin.x) / _scaleX;
float cursorY = (_viewPortRect.origin.y + _viewPortRect.size.height - _mouseY) / _scaleY;
the cursorX and cursorY is in OpenGL coordinates
in the code of CCEventMouse.cpp
// returns the current touch location in OpenGL coordinates
Vec2 EventMouse::getLocation() const
{
return Director::getInstance()->convertToGL(_point);
}
the _point is already in OpenGL coordinates due to cursorX and cursorY, and convertToGL change it to screen coordinates.
I think the issue #14150 is the same bug. @minggo