繁体   English   中英

glfwSetCursorPosCallback 在另一个类中运行

[英]glfwSetCursorPosCallback to function in another class

我真的被困住了:

我有 mainWindow 并且在主游戏循环中我做:

// poll for input
glfwPollEvents();

this->controls->handleInput(window, world->getPlayer());
glfwSetCursorPosCallback(window, controls->handleMouse);

我想要做的是让一个类负责控件并让这个类也处理鼠标。

我总是得到:

'Controls::handleMouse': function call missing argument list; use '&Controls::handleMouse' to create a pointer to member

现在,当我尝试这个时,我得到:

'GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow *,GLFWcursorposfun)' : cannot convert argument 2 from 'void (__thiscall Controls::* )(GLFWwindow *,double,double)' to 'GLFWcursorposfun'

不确定我在这里做错了什么,因为 GLFWcursorposfun 只是一个带有 GLFWwindow 和两个双打的 typedef。

由于该函数在另一个类中,我尝试为它创建一个原型,例如:

class Controls {
    void handleInput(GLFWwindow *window, object *gameObject);
    void handleMouse(GLFWwindow *window, double mouseXPos, double mouseYPos);
};

但无济于事。

编辑:当然,如果我将函数设为静态,我可以将其设置为 &Controls::handleMouse,但我宁愿能够使用它们操纵的不同摄像机和游戏对象创建多个控件对象。

另外,如何获得正确的相机/游戏对象数据呢?

您不能将类的成员函数作为函数传递。 glfwSetCursorPosCallback它期待一个函数并抛出错误,因为它获得了一个成员函数。

换句话说,您希望提供一个全局函数并将其传递给glfwSetCursorPosCallback

如果您真的希望控件对象获得光标位置回调,您可以将 Controls 的实例存储在全局变量中并将回调传递给该实例。 像这样的东西:

static Controls* g_controls;

void mousePosWrapper( double x, double y )
{
    if ( g_controls )
    {
        g_controls->handleMouse( x, y );
    }
}

然后当您调用glfwSetCursorPosCallback您可以传递mousePosWrapper函数:

glfwSetCursorPosCallback( window, mousePosWrapper );

我的解决方案:不要使用回调设置器。 相反,我执行以下操作:

glfwPollEvents();

this->controls->handleInput(window, mainObj);
this->controls->handleMouse(window, mainObj);

在 handleMouse 我做:

GLdouble xPos, yPos;
glfwGetCursorPos(window, &xPos, &yPos);

另一种解决方案是将指向controls的指针与GLFWindow相关联。 请参阅glfwSetWindowUserPointer

可以通过glfwGetWindowUserPointerGLFWWindow对象一次检索指针。 当然,返回类型是void*并且必须转换为Controls*

可以使用Lambda 表达式代替全局函数或静态方法。 例如:

glfwSetWindowUserPointer(window, this->controls);

glfwSetCursorPosCallback( window, [](GLFWwindow *window, double x, double y)
{
    if (Controls *controls = static_cast<Controls*>(glfwGetWindowUserPointer(window)))
        controls->handleMouse(window, x, y);
} );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM